0

我正在尝试创建一个组合图,其中包括geom_point所有点中的一个以及使用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)

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 列中)。我也尝试了一些尝试对数据进行子集化,但是我未能成功保留点但删除了形状。

代码输出

4

2 回答 2

1

每个geom_*函数都有一个数据参数,您可以使用它来覆盖前一层的数据。只需过滤类列中的 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 包于 2021-06-10 创建 (v2.0.0 )

于 2021-06-10T17:45:38.243 回答
0

如果要完全删除包含 NA 的行,只需使用drop_natidyverse 中的函数即可。使用管道运算符%>%,您可以将删除了 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)
于 2021-06-10T15:42:59.577 回答