在ggplot2中隐藏单个几何图形的图例 [英] Hide legend for a single geom in ggplot2

查看:96
本文介绍了在ggplot2中隐藏单个几何图形的图例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将相同的变量(颜色)映射到两个不同几何中的颜色.我希望它们要么出现在单独的图例(DHJ和EFI)中,要么最好完全跳过第二个图例(对于E,F和I).目前,R将两者混合在一起,并给了我一个图例,该图例按字母顺序列出了DEFHIJ.所有这些都混合在一起.

I map the same variable (color) to color in two different geoms. I want them either to appear in separate legends (DHJ and EFI) or preferably just skip the second legend (for E, F, and I) altogether. Currently, R mixes the two together and gives me a legend that lists DEFHIJ in alphabetical order all mixed together.

基本上,我想将今天的点绘制到一些使用标准数据集的平滑线上.我不想对平滑线有一个传说-我们都熟悉它们,它们在我们所有图形上都是标准的.我只想要一个传说来说明要点.

Basically, I want to graph today's points onto some smoothed lines that use a standard dataset. I don't want there to be a legend for the smoothed lines - we are all familiar with them and they are standard on all our graphs. I just want a legend for the points only.

我已经按照其他地方的建议尝试过 show.legend = FALSE ,但这似乎没有效果. guides(color = FALSE)删除了整个图例.

I've tried show.legend = FALSE as suggested elsewhere, but that doesn't seem to have an effect. guides(color = FALSE) removes the entire legend.

代表:

library(tidyverse)

set1 <- diamonds %>%
  filter(color %in% c("D", "H", "J")) 

set2 <- diamonds %>%
  filter(color %in% c("E", "F", "I")) 

ggplot() +
  geom_point(data = set1, 
             aes(x = x, y = y, color = color)) +
  geom_smooth(data = set2, 
              show.legend = FALSE, 
              aes(x = x, y = y, color = color))

这是生成的图.图例中包含所有6个字母,而不仅仅是DHJ.

Here is the graph that is produced. It has all 6 letters in the legend, instead of only DHJ.

推荐答案

如果您希望图例仅显示一个数据集中的颜色,则可以通过在 scale_color_discrete中设置 breaks 来实现()设置为这些值.

If you want the legend to show only the colors from one dataset you can do so by setting the breaks in scale_color_discrete() to those values.

... +
     scale_color_discrete(breaks = unique(set1$color) )

如果您不使用线条的颜色,因为这是标准的背景信息,则可以通过使用 geom_smooth()中的 group 来添加线条,而不是颜色.(如果您希望能够区分行,请参见 linetype .)

If you aren't using the colors of the lines, since this is standard background info, you could add the lines by using group ingeom_smooth() instead of color. (Also see linetype if you wanted to be able to tell the lines apart.)

ggplot() +
     geom_point(data = set1, 
                aes(x = x, y = y, color = color)) +
     geom_smooth(data = set2, 
                 aes(x = x, y = y, group = color)) 

这篇关于在ggplot2中隐藏单个几何图形的图例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆