ggplot2 删除某些 geoms 的 NA

ggplot2 removing NA for certain geoms

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

x <- c(10, 12, 4, 18, 6, 9, 2, 2, 7, 23, 13, 13, 11, 6, 22)
y <- c(3, 2, 12, 15, 23, 20, 6, 21, 6, 8, 15, 19, 10, 18, 14)
group <- c("a", "b", "b", "b","b","b","b", "c", "c", "c","c","c", "c", "d", "e")
class <- c(NA, "1", "1","1","1","1","1","2","2","2","2","2","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 列中)。我也玩了一些尝试对数据进行子集化,但是我在保留点但删除形状方面一直没有成功。

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

df %>%
drop_na() %>%
ggplot(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)

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

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