【发布时间】:2014-04-05 21:18:26
【问题描述】:
我在这里的某个地方找到了在 ggplot2 中创建 PCA 双图的代码。我做了一些小的修改,但我仍然需要改进。
代码如下:
PCbiplot2 <- function(res.pca, x="Dim.1", y="Dim.2") {
if(!require(ggplot2)) install.packages("ggplot2")
# res.pca being a PCA object
data <- data.frame(obsnames=row.names(res.pca$ind$coord), res.pca$ind$coord)
plot <- ggplot(data, aes_string(x=x, y=y)) + geom_text(size=3, aes(label=obsnames))
plot <- plot + geom_hline(aes(0), size=.2) + geom_vline(aes(0), size=.2)
datapc <- data.frame(varnames=rownames(res.pca$var$coord), res.pca$var$coord)
mult <- min(
(max(data[,y]) - min(data[,y])/(max(datapc[,y])-min(datapc[,y]))),
(max(data[,x]) - min(data[,x])/(max(datapc[,x])-min(datapc[,x])))
)
datapc <- transform(datapc,
v1 = .7 * mult * (get(x)),
v2 = .7 * mult * (get(y))
)
plot <- plot + coord_equal() + geom_text(data=datapc, aes(x=v1, y=v2, label=varnames), size = 3, vjust=1.5, color="red")
plot <- plot + geom_segment(data=datapc, aes(x=0, y=0, xend=v1, yend=v2), arrow=arrow(length=unit(0.2,"cm")), alpha=0.75, color="red")
plot <- plot + theme(panel.background = element_rect(fill='white', colour='black'))
plot
}
在图中使用此代码轴名称为“Dim.1”和“Dim.2”。我需要显示尺寸可变性的百分比。此信息位于 Dim.1 的 res.pca$eig[1,2] 和 Dim.2 的 res.pca$eig[2,2] 中,但我不知道如何将此信息输入到图表中。
【问题讨论】:
-
你试过
labs(x=as.character(res.pca$eig[1,2]), y=as.character( res.pca$eig[2,2]))吗?