ggplot2 删除某些几何图形的 NA

问题描述

我正在尝试使用 geom_point 创建一个包含所有点的 geom_encircle 和围绕数据组的多边形的组合图。但是,我只想包围特定的群体。我在下面有一些示例代码来帮助说明。

x <- c(10,12,4,18,6,9,2,7,23,13,11,22)
y <- c(3,15,20,21,8,19,10,14)
group <- c("a","b","c","d","e")
class <- c(NA,"1","2",NA,NA)

df <- as.data.frame(cbind(x,y,group,class))
df$x <- as.numeric(df$x)
df$y <- as.numeric(df$y)



library(ggplot2)
library(ggalt)

ggplot(df,aes(x,y)) +
  geom_point(aes(color = group)) +
  geom_encircle(aes(fill = class),s_shape = 1,expand = 0,alpha = 0.2,color = "black",na.rm = TRUE,show.legend = FALSE)

下图是我得到的,但是,我不想要灰色三角形,只想要蓝色和红色形状。我认为设置 na.rm = TRUE删除 geom_encircle 的那些行,但事实并非如此(我假设 NA 需要在 x 或 y 列中)。我也尝试过对数据进行子集化,但未能成功保留点但删除了形状。

output of code

解决方法

每个 geom_* 函数都有一个数据参数,您可以使用它来覆盖前一层的数据。只需过滤类列中的 NA 并在 geom_encircle 函数中使用过滤后的数据:

x <- c(10,12,4,18,6,9,2,7,23,13,11,22)
y <- c(3,15,20,21,8,19,10,14)
group <- c("a","b","c","d","e")
class <- c(NA,"1","2",NA,NA)

df <- as.data.frame(cbind(x,y,group,class))
df$x <- as.numeric(df$x)
df$y <- as.numeric(df$y)



library(ggplot2)
library(ggalt)
#> Registered S3 methods overwritten by 'ggalt':
#>   method                  from   
#>   grid.draw.absoluteGrob  ggplot2
#>   grobHeight.absoluteGrob ggplot2
#>   grobWidth.absoluteGrob  ggplot2
#>   grobX.absoluteGrob      ggplot2
#>   grobY.absoluteGrob      ggplot2

ggplot(df,aes(x,y)) +
  geom_point(aes(color = group)) +
  geom_encircle(data = df[!is.na(df$class),],aes(fill = class),s_shape = 1,expand = 0,alpha = 0.2,color = "black",na.rm = TRUE,show.legend = FALSE)

reprex package (v2.0.0) 于 2021 年 6 月 10 日创建

,

如果您想完全删除包含 NA 的行,您可以简单地使用 tidyverse 中的 drop_na 函数。使用管道运算符 %>%,您可以将删除了 NA 行的数据框直接传递到 ggplot 对象中。

df %>%
drop_na() %>%
ggplot(aes(x,y)) +
geom_point(aes(color = group)) +
geom_encircle(aes(fill = class),show.legend = FALSE)