【问题标题】:Trying to add legend using geom_abline尝试使用 geom_abline 添加图例
【发布时间】:2020-02-13 07:01:32
【问题描述】:

我有一个数据框,保存为df,其中有两列我想绘制的点。另外,我想在情节上绘制两条线,并希望这些线有一个图例。这是我的代码:

ggplot(df, aes(x = x, y = y)) + 
  geom_point(color = "black", shape = 16, alpha = 1) +
  scale_x_continuous(name = "x", limits = c(-5, 5)) + 
  scale_y_continuous(name = "y", limits = c(-5, 5)) +
  geom_abline(intercept = 0, slope = 4/3, linetype = "dashed", 
              color = "gray40", size = 1, aes(colour = "XNULL")) + 
  geom_abline(intercept = 0, slope = 0, linetype = "dotted", 
              color = "gray40", size = 1, aes(colour = "YNULL")) +
  scale_color_manual(name = "", values = c("XNULL" = "red", "YNULL" = "blue")) +
  theme(panel.background = element_rect(fill = "white"),
        panel.border = element_rect(colour = "black", fill = NA, size = 1),
        legend.position = "bottom")

但是,当我运行它时,没有出现图例(我希望在底部显示图例)。关于我做错了什么的任何建议?我是使用 ggplot2 的新手,我在其他论坛上查找的解决方案都没有帮助。

【问题讨论】:

    标签: r ggplot2 legend


    【解决方案1】:

    您可以尝试创建另一个 data.frame 来包含有关您的 ablines 的信息:

    df = data.frame(x=runif(10),y=runif(10))
    df2 = data.frame(intercept=0,slope=c(4/3,0),type=c("XNULL","YNULL"))
    

    然后我们可以调用geom_abline指定aes以便我们可以使用

    ggplot(df, aes(x = x, y = y)) + 
    geom_point(color = "black", shape = 16, alpha = 1) +
    scale_x_continuous(name = "x", limits = c(-5, 5)) + 
    scale_y_continuous(name = "y", limits = c(-5, 5)) +
    geom_abline(data=df2,aes(intercept=intercept,slope=slope,
    linetype=type,col=type),size = 1) +
    scale_color_manual(name = "", values = c("XNULL" = "red", "YNULL" = "blue")) +
    scale_linetype_manual(name = "", values = c("XNULL" = "dashed", "YNULL" = "dotted")) +
    theme(panel.background = element_rect(fill = "white"),
          panel.border = element_rect(colour = "black", fill = NA, size = 1),
    legend.position = "bottom")
    

    【讨论】:

      【解决方案2】:

      来自文档:

      这些geoms 的行为与其他geoms 略有不同。你可以提供 参数有两种方式:要么作为图层函数的参数, 或通过美学。如果您使用参数,例如geom_abline(截距= 0,slope = 1),然后geom在幕后制作一个新的数据框 仅包含您提供的数据。

      显然,您必须在aes 中指定interceptslope,才能正常工作。

      library(ggplot2)
      
      ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width)) + 
        geom_point() +
        coord_cartesian(xlim = c(0,10), ylim = c(0,10)) +
        geom_abline(aes(intercept = 0, slope = 0, color = "X"), linetype = "dotted") +
        geom_abline(aes(intercept = 0, slope = 4/3, color = "Y"),linetype = "dashed") +
        scale_color_manual(values = c(X = 'grey', Y = 'black'))
      

      reprex package (v0.3.0) 于 2020-02-12 创建

      【讨论】:

      • 顺便提一下,您可以将geom_abline(aes(intercept = 0, slope = 0, color = "X")...) 替换为geom_hline(aes(yintercept = 0 ... 而无需斜率参数。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-13
      • 2021-12-29
      相关资源
      最近更新 更多