ggplot2使用geom_encircle时如何移除NA值仅保留指定组环绕多边形
解决方法
问题根源是geom_encircle的na.rm参数仅对x、y列的缺失值生效,不会自动过滤fill映射列class的NA值,因此class为NA的行仍然会被识别为单独分组绘制多余的轮廓。
要实现保留全部散点、仅绘制class非空分组的环绕效果,只需要在geom_encircle层单独传入过滤掉class为NA的子集即可,不会影响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层使用筛选后的数据 geom_encircle(data = ~.x[!is.na(.x$class), ], aes(fill = class), s_shape = 1, expand = 0, alpha = 0.2, color = "black", show.legend = FALSE)
代码中~.x[!is.na(.x$class), ]是ggplot2的语法糖,表示基于全局传入的数据集df做筛选,也可以直接替换为df[!is.na(df$class), ],二者效果完全一致。
内容的提问来源于stack exchange,提问作者Stavrum
相关产品推荐
相关产品推荐

