使用vegan包绘制CCA图:如何添加数据集X的样本点?
问题:Vegan包CCA图无法显示样本点
我有两个数据框X和Y,用vegan包绘制典型相关分析(CCA)图时,运行cca()函数后仅能显示Y的向量名称,看不到X对应的样本点(命名为p1、p2…)。样本数量不多,希望在图中添加这些样本点。
原代码:
library('CCA') library('fastDummies') library('vegan') df <- read.csv("main.csv", encoding = "UTF-8", sep=";") X <- df["Sign"] Y <- df['Discip'] X <- dummy_cols(X, remove_selected_columns = TRUE) Y <- dummy_cols(Y, remove_selected_columns = TRUE) names(X) <- gsub(".*\_", "", names(X)) names(Y) <- gsub(".*\_", "", names(Y)) cc_results <- cca(X, Y) plot(cc_results, xlim=c(-50, 75), ylim=c(-50, 50))
数据示例:
> dput(head(X)) structure(list(Balance = c(0L, 0L, 0L, 0L, 0L, 0L), Belier = c(0L, 0L, 0L, 0L, 0L, 1L), Cancer = c(0L, 0L, 0L, 0L, 0L, 0L), Capricorne = c(0L, 0L, 0L, 0L, 0L, 0L), Gemeaux = c(0L, 0L, 0L, 0L, 0L, 0L), Lion = c(0L, 0L, 0L, 0L, 0L, 0L), Poissons = c(0L, 0L, 0L, 0L, 0L, 0L), Sagittaire = c(1L, 0L, 1L, 0L, 0L, 0L), Scorpion = c(0L, 1L, 0L, 1L, 0L, 0L), Taureau = c(0L, 0L, 0L, 0L, 0L, 0L), Verseau = c(0L, 0L, 0L, 0L, 1L, 0L), Vierge = c(0L, 0L, 0L, 0L, 0L, 0L)), row.names = c(NA, 6L), class = "data.frame") > dput(head(Y)) structure(list(Chirurgie = c(0L, 0L, 0L, 0L, 0L, 0L), Imagerie = c(0L, 0L, 0L, 0L, 0L, 0L), Laboratoire = c(0L, 0L, 0L, 0L, 0L, 0L), `Medecine generaliste` = c(0L, 0L, 0L, 0L, 0L, 0L), `Medecine specialiste` = c(1L, 1L, 1L, 1L, 1L, 1L)), row.names = c(NA, 6L), class = "data.frame")
解决方案
Vegan的cca()默认绘图不会自动展示样本点(观测值),需要手动提取样本得分并添加到图中:
- 提取样本得分:CCA结果的
$scores$sites存储了每个样本在CCA轴上的坐标 - 绘制样本点:用
points()添加样本点,可自定义样式 - 添加样本标签:用
text()标注样本名称(如p1、p2…)
修改后的完整代码:
library('CCA') library('fastDummies') library('vegan') df <- read.csv("main.csv", encoding = "UTF-8", sep=";") X <- df["Sign"] Y <- df['Discip'] X <- dummy_cols(X, remove_selected_columns = TRUE) Y <- dummy_cols(Y, remove_selected_columns = TRUE) names(X) <- gsub(".*\_", "", names(X)) names(Y) <- gsub(".*\_", "", names(Y)) cc_results <- cca(X, Y) # 绘制基础CCA图 plot(cc_results, xlim=c(-50, 75), ylim=c(-50, 50)) # 提取样本得分 sample_scores <- cc_results$scores$sites # 绘制样本点(红色实心圆) points(sample_scores, pch = 16, col = "red", cex = 1) # 添加样本标签,位置在点上方,字号0.8 text(sample_scores, labels = paste0("p", rownames(sample_scores)), pos = 3, cex = 0.8)
说明
pch = 16表示用实心圆作为点样式,可替换为其他数字(如1是空心圆)col设置点的颜色,可根据需求调整pos = 3指定标签在点的上方,可选值1(下)、2(左)、3(上)、4(右)- 如果样本名称已经是p1、p2…,直接用
labels = rownames(sample_scores)即可
内容的提问来源于stack exchange,提问作者glouis
相关产品推荐
相关产品推荐

