【问题标题】:Add legend for abline to ggplot geom_point将 abline 的图例添加到 ggplot geom_point
【发布时间】:2020-03-25 02:00:57
【问题描述】:

我想添加一个图例,它只描述我的情节中的线条,类似于这个:

library(ggplot)

df<-as.data.frame(cbind(seq(1:10), seq(from=2, to=20, 2)))
ggplot(data=df, aes(V1, V2))+geom_point()+
  geom_abline(intercept=0, slope=1)

我只想将 abline 添加到图例中。我已经尝试使用 geom_line,但是当我调整绘图的 x 和 ylims 时它消失了。 ggplot2 没有从头开始构建类似于 lattice 的图例的选项,是吗?

【问题讨论】:

    标签: r ggplot2 legend


    【解决方案1】:

    您可以将 geom_abline 参数包装在 aes() 中并添加一个颜色元素,然后在 scale_color_manual() 调用中对其进行控制:

       ggplot(data=df, aes(V1, V2)) +
          geom_point() +
          geom_abline(aes(color="whatever", intercept=0, slope=1)) +
          scale_color_manual(values = "red") +
          labs(color=NULL)
    

    【讨论】:

      【解决方案2】:

      或者你可以用两种不同的颜色来做:

      ggplot(data = df, aes(color="red", V1, V2)) + geom_point() + 
        geom_abline(aes(intercept = 0, slope = 1, color="blue")) + 
        scale_color_manual(values = c("red", "blue")) +
        labs(color=NULL)
      

      enter image description here

      【讨论】:

      • 谢谢,现在我的图例中有一行。但是,现在我的图例中有三行;一个用于 abline,两个用于数据点组。是否可以将数据点的线变成选择的 pch?在我的情况下 16.
      • 我通过使用网格添加完全自定义的图例解决了这个问题。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多