如何在 PCA 图中绘制不规则形状?

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

我想应用PCA方法可视化脂肪酸数据集,如何绘制不规则形状,而不是椭圆区域?我试图理解PCA代码中的

ellipse.type
,但是,它们都无法引导出图中的目标形状。

我想画的图形如下: aimed PCA figure 1 aimed PCA figure 2

示例代码:

# Load libraries
library(ggplot2)
library(dplyr)

# Assuming pca_data is the output from prcomp with PC1 and PC2 columns and 'group' for categories
# Replace 'your_data' with your actual data frame and 'group' with your actual grouping variable

# Example PCA data
pca_data <- data.frame(PC1 = rnorm(50), PC2 = rnorm(50), group = rep(c("A", "B", "C"), length.out = 50))

# Plot with smoother ellipses
ggplot(pca_data, aes(x = PC1, y = PC2, color = group, fill = group)) +
  geom_point(size = 3) +
  stat_ellipse(aes(group = group), level = 0.99, type = "t", linetype = "solid", alpha = 0.2) +
  labs(x = "PC1", y = "PC2") +
  theme_minimal()

使用

factoextra
包的另一个示例代码:

fviz_pca_biplot(pca_data, 
                label="var", 
                labelsize=4,#FA text size
                col.var="black",#FA text color
                arrowsize=0.5,#arrow size
                repel=T,#avoid text overlapping
                pointsize=2.5,
                mean.point=F,
                habillage=Group,
                addEllipses=TRUE,
                #ellipse.type="convex",
                #ellipse.type="norm",
                ellipse.type="t",
                #ellipse.type="confidence",
                ellipse.level=0.75,
                alpha.ind=0.8,
                ellipse.alpha=0.1)
r ggplot2 pca ellipse factoextra
1个回答
0
投票

不完全是你想要的,但一种选择是使用

ggforce::geom_mark_hull
在点组周围绘制凸包:

library(ggplot2)
library(ggforce)

set.seed(123)

pca_data <- data.frame(
  PC1 = rnorm(50), PC2 = rnorm(50),
  group = rep(c("A", "B", "C"), length.out = 50)
)

ggplot(pca_data, aes(x = PC1, y = PC2, color = group, fill = group)) +
  geom_point(size = 3) +
  ggforce::geom_mark_hull(aes(group = group),
    concavity = 0,
    radius = unit(5, "mm"),
  ) +
  labs(x = "PC1", y = "PC2") +
  theme_minimal() +
  coord_cartesian(clip = "off")

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