首页 > 解决方案 > 尝试使用 geom_abline 添加图例

问题描述

我有一个数据框,另存为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我在其他论坛上查找的解决方案都没有帮助。

标签: rggplot2legend

解决方案


从文档中:

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

显然,您必须指定interceptand slopeinaes才能正常工作。

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 包于 2020-02-12 创建(v0.3.0)


推荐阅读