ggplot绘制PCA分析图时未显示全部24个样本数据点的问题
PCA可视化样本"缺失"问题解决
用ggplot绘制PCA分析结果时,明明数据框有24条样本观测,但图表只显示了16个点。
我的代码:
ggplot(data) + aes(x=PC1, y=PC2) + geom_point(size=3) + coord_fixed() + theme_bw()
数据框:
PC1 PC2 <dbl> <dbl> 1 -40.8 -20.6 2 -40.6 -19.0 3 -40.8 -20.6 4 8.01 -38.1 5 8.52 -36.3 6 8.01 -38.1 7 -39.7 -6.11 8 -38.1 -5.76 9 -39.7 -6.11 10 18.3 -33.9 11 17.9 -33.3 12 18.3 -33.9 13 -32.9 11.2 14 -31.7 9.49 15 -32.9 11.2 16 50.9 -4.98 17 49.4 -5.64 18 50.9 -4.98 19 -38.7 56.9 20 -38.0 54.9 21 -38.7 56.9 22 74.8 36.3 23 72.8 34.1 24 74.8 36.3
问题本质:
不是样本没被绘制,而是大量样本的PC1和PC2坐标完全重复,比如第1/3行、4/6行、7/9行等,这些点在图上完全重叠,看起来只显示了16个独特坐标的点。
解决办法:
- 添加抖动效果:让重叠点轻微偏移,展示所有样本
ggplot(data) + aes(x=PC1, y=PC2) + geom_point(size=3, position = position_jitter(width = 0.5, height = 0.5)) + coord_fixed() + theme_bw()
- 添加样本标签:用行号标记每个点,直观看到重叠情况
ggplot(data) + aes(x=PC1, y=PC2, label = rownames(data)) + geom_point(size=3) + geom_text(vjust = 1.5) + coord_fixed() + theme_bw()
- 统计重叠数量:用点的大小表示该位置的样本数,清晰展示密度
ggplot(data) + aes(x=PC1, y=PC2) + geom_count(size=3) + coord_fixed() + theme_bw()
内容的提问来源于stack exchange,提问作者Maria
相关产品推荐
相关产品推荐

