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?

我想要的输出是:

推荐答案

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

library(ggplot2)

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

enter image description here

R相关问答推荐

给定R中另一行中的值,如何插补缺失值

编码变量a、b、c以匹配来自另一个数据点的变量x

格点中指数、双曲和反双曲模型曲线的正确绘制

如何写一个R函数来旋转最后n分钟?

在ggplot2中更改小提琴情节的顺序

如何写商,水平线,在一个单元格的表在R

Select 季度月值

用约翰逊分布进行均值比较

更新R中的数据表(使用data.table)

自定义gggraph,使geom_abline图层仅在沿x轴的特定范围内显示

将工作目录子文件夹中的文件批量重命名为顺序

`-`是否也用于数据帧,有时使用引用调用?

在r中整理图例和堆叠图的问题

填充图例什么时候会有点?

如何更改包中函数中的参数?

具有自定义仓位限制和计数的GGPLATE直方图

如何在shiny 的应用程序 map 视图宣传单中可视化单点

位置_道奇在geom_point图中不躲避

在使用ggplot2的情况下,如何在使用coord_trans函数的同时,根据未转换的坐标比来定位geom_瓷砖?

我怎么才能把一盘棋变成一盘棋呢?