【问题标题】:Fail to add linear regression line in barplot无法在条形图中添加线性回归线
【发布时间】:2020-03-13 15:39:00
【问题描述】:

我有一些关于不同时间段温度百分比的数据,我想创建一个显示这些百分比的条形图,然后添加一个线性回归线来显示趋势。虽然我设法得到了第一张图,但我没有添加直线回归线

基本上我尝试用这些 tx_1 数据制作条形图

tx_1<-c(0.055,0.051,0.057,0.049,0.061,0.045)

mypath<-file.path("C:\\tx5\\1.jpeg")
jpeg(file = mypath,width = 1200, height = 600)
plot.dim<-barplot(get(name),
                  space= 2,
                  ylim=c(0,0.15),
                  main = "Percentage of days when Tmax < 5th percentile",
                  xlab = "Time Periods",
                  ylab = "Percentage",
                  names.arg = c("1975-1984", "1985-1990", "1991-1996", "1997-2002", "2003-2008", "2009-2014"),
                  col = "darkred",
                  horiz = FALSE)
dev.off()

我也尝试过使用 ggplot,但没有成功

【问题讨论】:

  • 您可以通过首先使用lm 函数计算线性模型,然后使用abline 函数添加线来实现这一点(参见here 示例)。不过,我真的不确定这种模型的有效性……

标签: r bar-chart linear-regression lm


【解决方案1】:

在这里,我包含了连接每个观察值的线和整体最佳线性拟合线。希望这会有所帮助。

library(tidyverse)

year <- tribble(~ Year,~ Percent,
        94,0.055,
        95,0.051,
        96,0.057,
        97,0.049,
        98,0.061,
        99,0.045)

ggplot(year,aes(Year,Percent)) + 
  geom_bar(stat = "identity") + 
  geom_line() + 
  geom_smooth(method = "lm",se = F)

【讨论】:

  • 如果你查看 OP 的问题,x 轴标签是分类的。所以如果你有它而不是 94,95... 你的代码还能工作吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-01-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-03
  • 2021-01-14
相关资源
最近更新 更多