使用 ggplot2 绘制 pca biplot [英] Plotting pca biplot with ggplot2

查看:42
本文介绍了使用 ggplot2 绘制 pca biplot的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否可以使用 ggplot2 绘制 pca biplot 结果.假设我想用 ggplot2 显示以下双标结果

I wonder if it is possible to plot pca biplot results with ggplot2. Suppose if I want to display the following biplot results with ggplot2

fit <- princomp(USArrests, cor=TRUE)
summary(fit)
biplot(fit)

任何帮助将不胜感激.谢谢

Any help will be highly appreciated. Thanks

推荐答案

也许这会有所帮助——它改编自我前段时间写的代码.它现在也绘制箭头.

Maybe this will help-- it's adapted from code I wrote some time back. It now draws arrows as well.

PCbiplot <- function(PC, x="PC1", y="PC2") {
    # PC being a prcomp object
    data <- data.frame(obsnames=row.names(PC$x), PC$x)
    plot <- ggplot(data, aes_string(x=x, y=y)) + geom_text(alpha=.4, size=3, aes(label=obsnames))
    plot <- plot + geom_hline(aes(0), size=.2) + geom_vline(aes(0), size=.2)
    datapc <- data.frame(varnames=rownames(PC$rotation), PC$rotation)
    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 = 5, vjust=1, 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
}

fit <- prcomp(USArrests, scale=T)
PCbiplot(fit)

您可能想要更改文本的大小,以及透明度和颜色,以适应口味;使它们成为函数的参数会很容易.注意:我突然想到这适用于 prcomp,但您的示例适用于 princomp.同样,您可能需要相应地调整代码.注 2:geom_segment() 的代码是从评论链接到 OP 的邮件列表帖子中借用的.

You may want to change size of text, as well as transparency and colors, to taste; it would be easy to make them parameters of the function. Note: it occurred to me that this works with prcomp but your example is with princomp. You may, again, need to adapt the code accordingly. Note2: code for geom_segment() is borrowed from the mailing list post linked from comment to OP.

这篇关于使用 ggplot2 绘制 pca biplot的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆