简体   繁体   English

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

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

I'm trying to use ggplot with several different layers of lines, one using a color legend and the other using a linetype legend. 我正在尝试将ggplot与几个不同的线条层一起使用,一个使用颜色图例,另一个使用线型图例。 Unfortunately, it seems that both layers show up in both legends, as in the simple example below: 不幸的是,似乎两个图层都出现在两个图例中,如下面的简单示例所示:

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)

The code produces this plot: 代码生成此图:

There are already several similar questions, such but none of the proposed solutions fixes the issue in this example. 已经存在几个类似的问题,但是所提出的解决方案都没有解决该示例中的问题。 For example, this question was answered by simply eliminating a geom from all the legends, which is not what I want, while this question seems like it should be a solution to my problem, but my code above already incorporates the answer and I still see the problem. 例如,通过简单地从所有传说中删除geom来回答这个问题 ,这不是我想要的,而这个问题似乎应该是我的问题的解决方案,但我上面的代码已经包含了答案,我仍然看到问题。 So how I can tell ggplot to keep the vertical lines out of the color legend and the horizontal lines out of the linetype legend in the example above? 那么我怎么能告诉ggplot在上面的例子中保持颜色图例中的垂直线和线型图例中的水平线?

All you need is 所有你需要的是

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)

情节与正确的传说

ggplot2 takes its legend specifications from whatever is in aes . ggplot2aes任何内容中获取其传奇规范。 If it's outside aes but in the geom_* function, it will get plotted, but not put in the legend. 如果它在aes之外但在geom_*函数中,它将被绘制,但不会放在图例中。

If you specify show.legend = TRUE , it will override that behavior and plot a legend for everything; 如果指定show.legend = TRUE ,它将覆盖该行为并为所有内容绘制图例; you actually want show.legend = NA , which is the default. 你真的想要show.legend = NA ,这是默认值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM