我如何控制在 ggplot2 的哪些图例中显示哪些几何图形?

How can I control which geoms show up in which legends in ggplot2?

我正在尝试将 ggplot 与几个不同的线层一起使用,一个使用颜色图例,另一个使用线型图例。不幸的是,这两个层似乎都出现在两个图例中,如下面的简单示例所示:

hlines <- data.frame(Hline=c("a", "b"), y=c(-1,1))
vlines <- data.frame(Hline=c("x", "y"), x=c(-1,1))
ggplot() +
    geom_hline(data=hlines,
               aes(color=Hline, yintercept=y, linetype=NA),
               linetype="solid",
               show.legend=TRUE) +
    geom_vline(data=vlines,
               aes(linetype=Hline, xintercept=x, color=NA),
               color="black",
               show.legend=TRUE) +
    scale_color_hue(name="Hline color") +
    scale_linetype(name="Vline ltype") +
    xlim(-3, 3) + ylim(-3, 3)

代码生成此图:

已经有几个类似的问题,但是 none 提出的解决方案解决了这个例子中的问题。例如,this question was answered by simply eliminating a geom from all the legends, which is not what I want, while 似乎应该是我的问题的解决方案,但我上面的代码已经包含了答案,但我仍然看到了问题。那么在上面的示例中,我如何告诉 ggplot 将垂直线从颜色图例中取出,将水平线从线型图例中取出?

你只需要

ggplot() + 
    geom_hline(data = hlines, 
               aes(color = Hline, yintercept = y)) + 
    geom_vline(data = vlines, 
               aes(linetype = Hline, xintercept = x)) + 
    scale_color_hue(name = "Hline color") + 
    scale_linetype(name = "Vline ltype") + 
    xlim(-3, 3) + ylim(-3, 3)

ggplot2aes 中获取其图例说明。如果它在 aes 之外但在 geom_* 函数中,它将被绘制,但不会放入图例中。

如果您指定 show.legend = TRUE,它将覆盖该行为并为所有内容绘制图例;你实际上想要 show.legend = NA,这是默认值。