R语言 如何仅在图例中省略NA

bqf10yzr  于 2023-03-27  发布在  其他
关注(0)|答案(3)|浏览(207)
library("dplyr")
library("ggplot2")

让我们从这个简单的图开始:

faithful %>%
    ggplot(aes(waiting, eruptions, color = eruptions > 3)) +
    geom_point()

现在,让我们在类变量中引入一些缺失值:

faithful_with_missings <-
    faithful %>%
    mutate(eruptions_class = ifelse(eruptions > 3, '>3', '<=3'),
           eruptions_class = ifelse(rbinom(n(), 1, 0.9), eruptions_class, NA_character_))
           ##eruptions_class = as.factor(eruptions_class))
faithful_with_missings$eruptions_class %>% table(exclude = NULL)
#> .
#>  <=3   >3 <NA> 
#>   89  151   32

使用缺失项重做打印:

ggplot(faithful_with_missings, aes(waiting, eruptions, color = eruptions_class)) +
    geom_point()

我的问题是:有没有一种方法可以绘制NA点,但在图例中省略NA?
我想要的输出是:

z2acfund

z2acfund1#

您可以通过scale的breaks参数设置类别以显示在图例中。因此,要删除NA,您可以使用scale_color_discrete中的lambda函数来删除NA:

library(ggplot2)

ggplot(faithful_with_missings, aes(waiting, eruptions, color = eruptions_class)) +
  geom_point() +
  scale_color_discrete(breaks = ~ .x[!is.na(.x)])

3hvapo4f

3hvapo4f2#

另一个使用scale_color_manual的选项是知道NA颜色是grey50,并像这样指定breaks

library(ggplot2)
library(dplyr)

ggplot(faithful_with_missings, aes(waiting, eruptions, color = eruptions_class)) +
  geom_point() +
  scale_color_manual(values = c("red", "blue", "grey50"), breaks = c("<=3", ">3"))

创建于2023-03-25带有reprex v2.0.2
如果你想使用ggplot的标准颜色,你可以使用scales包中的hue_pal函数来获得两种颜色,如下所示:

library(ggplot2)
library(dplyr)

ggplot(faithful_with_missings, aes(waiting, eruptions, color = eruptions_class)) +
  geom_point() +
  scale_color_manual(values = c(hue_pal()(2), "grey50"), breaks = c("<=3", ">3"))

创建于2023-03-25带有reprex v2.0.2

gwo2fgha

gwo2fgha3#

下面是调整scale_color_manualtheme的另一种方法:

library(ggplot2)

  ggplot(faithful_with_missings, aes(waiting, eruptions, color = eruptions_class)) +
    geom_point() +
    scale_color_manual(values = c("blue", "red", "NA"),
                      limits = c("<=3",">3","")) +
    theme_bw()+
    theme(legend.background=element_blank())

相关问题