如何控制哪些geom出现在ggplot2中的哪些图例?

时间:2016-05-05 19:25:02

标签: r ggplot2 legend

我试图将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)

代码生成此图:

已经有几个类似的问题,但是这个提议的解决方案都没有解决这个例子中的问题。例如,this question只是通过简单地从所有传说中删除geom来回答,这不是我想要的,而this question似乎应该是我的问题的解决方案,但我上面的代码已经包含了答案,我仍然看到了问题。那么我怎么能告诉ggplot在上面的例子中保持颜色图例中的垂直线和线型图例中的水平线?

1 个答案:

答案 0 :(得分:4)

你需要的只是

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)

plot with proper legends

ggplot2aes中的任何内容中获取其图例规范。如果它在aes之外但在geom_*函数中,它将被绘制,但不会放在图例中。

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

相关问题