【问题标题】:How to create and align a base R Barplot with an abline regression line?如何创建基本 R Barplot 并将其与 abline 回归线对齐?
【发布时间】:2020-08-27 12:22:01
【问题描述】:

我正在尝试使用基本 R 代码以及使用 abline 的线性拟合来制作条形图,但似乎在使用 abline 时我没有得到正确的结果。至少,在查看回归线并将其与使用预测模型绘制一些线进行比较时,它还差得很远:

df <- data.frame(year = c(2018,2019,2020), PWI = c(64.7,71.3,75.2))
barplot(PWI~year, data = df, ylim = c(0,100))
text(x,y+2,labels=as.character(as.matrix(round(df,1))))

abline(lm(PWI~I(year-2018)), lty = "dashed", col = "red")

如何让 abline 与条形图对齐?

为了记录,我对基本 R 方法感兴趣,它的线条表现得像 abline。可以通过以下方式在 ggplot 中完成:

coeff <- coefficients(lm(PWI~year, data = df))
ggplot(df,aes(year,PWI)) + 
  geom_bar(stat = "identity") + 
  geom_abline(intercept = coeff[1], slope = coeff[2])

【问题讨论】:

    标签: r regression bar-chart linear-regression


    【解决方案1】:

    将 barplot 的输出保存在变量中。它包含每个条的中心

    out <- barplot(PWI~year, data = df, ylim = c(0,100))
    abline(lm(PWI~I(out), data = df), lty = "dashed", col = "red")
    

    【讨论】:

    • 简单高效!
    【解决方案2】:

    所以这里发生的事情是 barplot 对 x 坐标做了一些魔术,这对 abline 来说是不一样的。

    df <- data.frame(year = c(2018,2019,2020), PWI = c(64.7,71.3,75.2))
    
    bp <- barplot(PWI~year, data = df, ylim = c(0,100))
    print(bp)
         [,1]
    [1,]  0.7
    [2,]  1.9
    [3,]  3.1
    

    这里的值是 barplot 使用的实际 x 坐标。我们可以像这样画出正确的斜线:

    df <- data.frame(year = c(2018,2019,2020), PWI = c(64.7,71.3,75.2))
    bp <- barplot(PWI~year, data = df, ylim = c(0,100))
    text(x,y+2,labels=as.character(as.matrix(round(df,1))))
    
    fit <- lm(PWI~I(year-2018), data = df)
    
    # manually compute the predictions 
    ycoords <- predict(fit)
    
    lines(bp, ycoords, col = 3, lty = 3)
    points(bp, ycoords, col = 3, lty = 3)
    

    这给了我:

    绿线现在是它应该在的位置。

    edit:请注意,barplot 可能会将年份变成一个因素(在您的示例中只需将 2020 更改为 3000)。因此,如果您以不同的间隔绘制某些内容,则该图可能会扭曲数据中的关系。

    【讨论】:

    • 这很好,但它不是你在我的问题中看到的那样。我已经用线(图片中显示的黑色虚线)完成了它,使用 x &lt;- barplot(PWI ~ year, data = df) yval &lt;- predict.lm(reg_pwi, yyy) lines(x = x, y = yval, lty = "dashed") 这就是我最初调查问题所在的方式。
    • 您评论中的代码与我回答中的代码没有本质区别。但是请注意,stackoverflow.com/a/63616223/4917834 不是在 PWI 上回归年份,而是在 PWI 上回归 bin 的中心。不过,这对于一个人物来说非常好。
    • 这可能是我需要的技术洞察力。垃圾箱的中心。谢谢!
    猜你喜欢
    • 2017-06-12
    • 2012-09-17
    • 1970-01-01
    • 2020-11-01
    • 2014-12-15
    • 2020-10-04
    • 2014-12-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多