【问题标题】:How to remove specific group from a plot but plot stays the same in R?如何从绘图中删除特定组但绘图在 R 中保持不变?
【发布时间】:2020-10-16 10:10:23
【问题描述】:
data('iris')
pca.irix <- PCA(iris[ ,1:4])
gg <- factoextra::fviz_pca_biplot(X = pca.irix, 
                             # samples
                             fill.ind = iris$Species, col.ind = 'black',
                             pointshape = 21, pointsize = 1.5,
                             geom.ind = 'point', repel = T,
                             geom.var = FALSE )

我想获得一个与上面的图完全相同但没有 setosa 的图。 我开始这样做了,但不知道如何继续

setosa_wo <- iris %>% 
             filter(Species != 'setosa')

gg + scale_x_continuous(limits = c((-2), 2)) + scale_y_continuous(limits = c((-2), 2))

如何从图中删除彩色组?但情节应该保持不变。

【问题讨论】:

    标签: r plot grouping pca


    【解决方案1】:

    从图中删除一个或任意数量的组的一种方法是过滤用于图层的数据,例如查看gg$layers 表明您的 PCA 图由六层组成,但只有前两层是用作填充颜色的组。因此,我只是过滤了这两层的数据,这给了我一个删除setosa 的图。

    编辑按照 @DaveArmstrong 的建议,我添加了他的代码以将轴的范围固定在原始范围上,并额外添加了原始颜色

    library(FactoMineR)
    library(ggplot2)
    
    pca.irix <- PCA(iris[ ,1:4])
    
    gg <- factoextra::fviz_pca_biplot(X = pca.irix, 
                                      # samples
                                      fill.ind = iris$Species, col.ind = 'black',
                                      pointshape = 21, pointsize = 1.5,
                                      geom.ind = 'point', repel = T,
                                      geom.var = FALSE )
    
    # First: Get the ranges
    yrg <- ggplot2::layer_scales(gg)$y$range$range
    xrg <- ggplot2::layer_scales(gg)$x$range$range
    
    # Filter the data
    gg$layers[[1]]$data <- dplyr::filter(gg$layers[[1]]$data, Fill. != "setosa")
    gg$layers[[2]]$data <- dplyr::filter(gg$layers[[2]]$data, Fill. != "setosa")
    
    gg + 
      # Set the limits to the original ones
      ggplot2::coord_cartesian(xlim=xrg, ylim=yrg, expand=FALSE) +
      # Add orignial colors
      ggplot2::scale_fill_manual(values = scales::hue_pal()(3)[2:3])
    

    reprex package (v0.3.0) 于 2020 年 10 月 16 日创建

    【讨论】:

    • 我认为除了上面的好答案之外,OP 还希望保持原来的 x 轴和 y 轴限制。您可以通过修改上述内容来做到这一点(必须在过滤数据之前计算 x 和 y 范围):yrg &lt;- layer_scales(gg)$y$range$rangexrg &lt;- layer_scales(gg)$x$range$rangegg + coord_cartesian(xlim=xrg, ylim=yrg, expand=FALSE)
    • @DaveArmstrong 嗨,戴夫。谢谢你的建议。我已将其添加到我的答案中,顺便还修复了填充颜色。最佳 S.
    猜你喜欢
    • 2012-09-30
    • 1970-01-01
    • 2013-07-02
    • 2015-09-09
    • 2013-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多