【问题标题】:Add regression line legend to geom_abline将回归线图例添加到 geom_abline
【发布时间】:2017-10-15 22:09:32
【问题描述】:

我已经编码了这个:

ggplot() + 
  geom_point(mapping = aes(x = X, y = y)) + 
    geom_abline(intercept = -0.9930872, slope = 0.4866284, colour = "red") + 
    geom_abline(intercept = -1, slope = 0.5, colour = "blue")

但似乎无法为我的最小二乘和人口回归线找到一个可行的图例。我尝试了各种堆栈溢出答案,但似乎没有什么能满足我的需求。

Add a legend to a ggplot2 scatter plot including additional lines

这看起来是最好的答案,但我无法让它工作!

有什么建议吗?

【问题讨论】:

    标签: r legend-properties


    【解决方案1】:
    set.seed(1234)
    X <- rnorm(20,sd=2.5)
    y <- -1+0.5*X+rnorm(20, sd=0.4)
    
    library(ggplot2)
    ggplot() + 
    geom_point(mapping = aes(x = X, y = y)) + 
    geom_abline(aes(intercept = -0.9930872, slope = 0.4866284, colour = "line1"), lwd=1) + 
    geom_abline(aes(intercept = -1, slope = 0.5, colour = "line2"), lwd=1) +
    scale_colour_manual(values=c("line1"="red","line2"="blue"))
    

    【讨论】:

    • 这看起来很完美!我明天试试...谢谢!
    【解决方案2】:

    稍作修改,您的代码就可以正常工作:

    ggplot() + 
    geom_point(mapping = aes(x = X, y = y)) + 
       geom_abline(aes(colour = "line_1",  intercept = -0.9930872, slope = 0.4866284)) + 
       geom_abline(aes(colour = "line_2", intercept = -1, slope = 0.5)) +
       scale_colour_manual(name = "lines", values = c("red", "blue")) +
       theme(legend.position = "bottom")
    

    添加图例位置以防您也想更改它。

    【讨论】:

      猜你喜欢
      • 2021-05-21
      • 1970-01-01
      • 1970-01-01
      • 2020-06-18
      • 2021-01-21
      • 1970-01-01
      • 1970-01-01
      • 2018-05-11
      相关资源
      最近更新 更多