【问题标题】:ggplot2 removing NA for certain geomsggplot2 删除某些几何图形的 NA
【发布时间】:2021-08-27 15:29:30
【问题描述】:

我正在尝试创建一个组合图,其中包括所有点的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 列中)。我也尝试了一些尝试对数据进行子集化,但是我未能成功保留点但删除了形状。

【问题讨论】:

    标签: r ggplot2 polygon na geom-point


    【解决方案1】:

    如果您想完全删除包含 NA 的行,您可以简单地使用 tidyverse 中的 drop_na 函数。使用管道运算符%&gt;%,您可以将删除了 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)
    

    【讨论】:

      【解决方案2】:

      每个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 package (v2.0.0) 于 2021-06-10 创建

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-10-12
        • 2019-06-22
        • 2016-08-31
        相关资源
        最近更新 更多