首页 > 解决方案 > 覆盖多个 fviz 集群

问题描述

我想在一个图(相同数据)中显示几个透明的叠加“fviz_cluster”图:

library(ggplot2)
library(dbscan)
library(factoextra)
d = cbind(iris$Sepal.Length, iris$Sepal.Width)
# cluster the data (could be k-means, or any other method)
clus = dbscan(d, eps=0.2, minPts=5)
fviz_cluster(clus, data=iris,
             choose.vars=c("Sepal.Length", "Sepal.Width"),
             ellipse.type="convex", geom="point", show.clust.cent=FALSE)

在此处输入图像描述

# cluster again with different parameters
clus2 = dbscan(d, eps=0.3, minPts=5)
# How would I overlay the outlines and shading of the 'clus2' clusters

在此处输入图像描述

所以我想要的是这两个图的叠加。我当然会改变第二个的调色板。有没有办法用“现成的” fviz_cluster 来做到这一点,还是我必须进入内部?我很惊讶 fviz_cluster 应该是“基于 ggplot2”的,但不允许对其图进行分层,除非我错过了一些东西。

标签: rggplot2plot

解决方案


粗略组合的集群

fviz_cluster()很高兴绘制任何东西,cluster因此data您可以粗略地组合数据并绘制它,但这并没有实现异常值功能,例如:

combined <- data.frame(cluster=clus1$cluster)
combined <- rbind(combined,
                  data.frame(cluster=ifelse(clus2$cluster > 0,
                                            clus2$cluster + max(combined$cluster),
                                            0)))
combined$data <- rbind(iris, iris)

fviz_cluster(combined,
             choose.vars=c("Sepal.Length", "Sepal.Width"),
             ellipse.type="convex",
             geom="point", show.clust.cent=FALSE)

fviz_cluster() 绘制两个粗略组合的集群

实现 dbscan 合并

您可以通过编写自己的函数来合并两个或多个dbscan对象,但这可能看起来不会比前面的示例好多少。

外部结合

ImageMagick 可以将图像混合在一起并改变颜色。我认为这不会很好地工作,因为点叠加和它们的外观会改变,使图例不完整,等等,但这里有一个例子:

convert AWRRa.png -modulate 100,100,120 \
    \( AN4Ng.png -alpha set -channel a -evaluate set 70% +channel \) \
    -compose over -composite blended.convert.png

问题中的两个图与 ImageMagick 相结合

动画时间!

该问题的切线答案,但值得通过gganimate或使用 ImageMagick 组合帧进行探索(取决于您的媒体)ggsave(),例如:

ggplot png 帧由 ImageMagick 组合为动画 gif

多个图像

放弃并使用grid.arrange()去多个地块是另一种选择!


推荐阅读