添加线条以连接图表中的单独集群

问题描述 投票:0回答:2

我在网上看到了这个简洁的主成分分析图,其中有将每个簇连接到中心点的线。

我使用了一个示例数据集来表明我已经添加了省略号,但是在网上查看之后,我认为这个PCA包目前不具备添加这些省略号的能力,并且在某些情况下,它被称为“星星”。有没有办法以某种方式绕过漏洞并将其添加到 PCA 图表中?

我在下面添加了一些示例代码,用于获取没有线路连接的部分。请对此提出建议。我最后的想法可能是使用 ggforce 或类似的东西?

library(factoextra)
data(iris)

res.pca <- prcomp(iris[,-5], scale=TRUE)

fviz_pca_ind(res.pca, label="none", alpha.ind=1, pointshape=19,habillage=iris$Species, addEllipses = TRUE, ellipse.level=0.95)

一些评论建议了这些网站,但虽然很接近,但有点不同,因为我尝试使用一个数据框,其中一列是我希望用于不同聚类的不同类别的列。

链接1

链接2

如有任何可能的建议,我们将不胜感激。

r pca
2个回答
1
投票

一个快速而肮脏的黑客是从

fviz_pca_ind()
的输出中的ggplot数据创建一个边df,然后用
geom_segment()
绘制它。

请注意,这在视觉上可能不是最佳的,因为您经常需要在节点之前绘制边缘,以便突出显示(即不隐藏)后者的位置。但除非重写

df_raw_pca_viz
fviz
绘图函数,这是获得您所要求的内容的快速方法。

尝试:

library(factoextra)
library(purrr)
library(dplyr)
data(iris)

res.pca <- prcomp(iris[,-5], scale=TRUE)

g1 <- fviz_pca_ind(res.pca, label="none", alpha.ind=1, pointshape=19,habillage=iris$Species, addEllipses = TRUE, ellipse.level=0.95)

df_edges <- 
  pluck(g1, "data") |> as_tibble() |>
  group_by(Groups) %>% 
  summarise(xend = mean(x), yend = mean(y)) |>
  left_join(y =  pluck(g1, "data"), 
            by = "Groups", 
            multiple = "all")

g1 +
  geom_segment(data = df_edges, aes(xend = xend, yend = yend, x = x, y = y, colour = Groups), alpha = 0.25)


0
投票

最近我开发了一个名为“GABB”的用户友好的 R 包,用于执行简单而漂亮的 PCA,包括从数据点到已识别组的重心的分段。使用 mtcars 数据集检查以下示例,如果您满意请告诉我:

library(GABB)

## Example of GABB package pipeline with the base data.set "mtcars" 
my.data <- mtcars

## Data preparation for RDA and PCA : tranformation and scaling of numeric/quantitative variables

prep_data(data = my.data, quantitative_columns = c(1:7), transform_data_method = "log", scale_data = T)

## Create PCA
library(FactoMineR)
my.pca <- FactoMineR::PCA(X = data_quant) 


## Create, display and save graphic output of individual and variable PCA

#Basic output with minimum required parameters
PCA_RDA_graphics(complete.data.set = initial_data_with_quant_transformed, PCA.object = my.pca, factor.names = c("vs", "am", "gear", "carb"))

#Advanced outputs (image below)
PCA_RDA_graphics(complete.data.set = initial_data_with_quant_transformed, PCA.object = my.pca, 
                 factor.names = c("vs", "am", "gear", "carb"), Biplot.PCA = TRUE,col.arrow.var.PCA = "grey",
                 Barycenter = TRUE, Segments = TRUE, Ellipse.IC = TRUE,
                 Barycenter.Ellipse.Fac1 = "vs", Barycenter.Ellipse.Fac2 = "am",
                 factor.colors = "vs", factor.shapes = "am",
                 Barycenter.factor.col = "vs", Barycenter.factor.shape = "am")

© www.soinside.com 2019 - 2024. All rights reserved.