【问题标题】:How can I control which geoms show up in which legends in ggplot2?如何控制 ggplot2 中的哪些图例中显示哪些几何图形?
【发布时间】:2016-08-31 17:18:10
【问题描述】:

我正在尝试将 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 是通过简单地从 all 图例中消除一个 geom 来回答的,这不是我想要的,而 this question 似乎应该是我的问题的解决方案,但我的代码上面已经包含了答案,我仍然看到了问题。那么在上面的示例中,如何告诉 ggplot 将垂直线保留在颜色图例之外,将水平线保留在线型图例之外?

【问题讨论】:

    标签: r ggplot2 legend


    【解决方案1】:

    你只需要

    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,这是默认值。

    【讨论】:

      猜你喜欢
      • 2021-11-12
      • 1970-01-01
      • 2021-08-27
      • 2016-06-02
      • 1970-01-01
      • 1970-01-01
      • 2011-10-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多