ggbiplot 重叠变量

ggbiplot overlapping variables

我无法得到不与 ggbiplot 重叠的变量标签

(使用 RStudio 1.1.463 和 R 版本 3.5.3)

我是 运行 具有 prcomp 的 pca,但我得到这种变量标签重叠:

这是一个例子:

library(ggbiplot)
data(wine)
wine_subset<-subset(wine[,c(6:7,9,12)])
wine.pca <- prcomp(wine_subset, scale. = TRUE)
print(ggbiplot(wine.pca, obs.scale = 1, var.scale = 1, groups = wine.class, ellipse = TRUE, circle = TRUE))

我试图解决从 ggrepel 包中添加此代码的问题:

library(ggrepel)
+geom_text_repel(aes(labels=colnames(wine_subset)))

但是returns出现以下错误:

Warning: Ignoring unknown aesthetics: labels Error: Aesthetics must be either length 1 or the same as the data (178): labels

在我看来,它正在尝试使用行标签,但我不需要在绘图中使用它们。我只需要变量标签。

这是一个技巧,它在其中一个变量名中添加了一个换行符,因此它不会与另一个变量名重叠:

library(ggbiplot)
data(wine)
wine_subset<-subset(wine[,c(6:7,9,12)])
colnames(wine_subset)[2] <- "\nFlav"  # new line
wine.pca <- prcomp(wine_subset, scale. = TRUE)
print(ggbiplot(wine.pca, obs.scale = 1, var.scale = 1, groups = wine.class, ellipse = TRUE, circle = TRUE))

请务必仅使用新列名进行绘图。

我找到了一个更好的解决方案 ggfortify 包,它有一个简单的参数 loadings.label.repel:

library(ggbiplot)   #just for using the same example database as before
library(ggfortify)

data(wine)

wine_subset<-subset(wine[,c(6:7,9,12)])

wine.pca <- prcomp(wine_subset, scale. = TRUE)

wine$wine.class <- wine.class    #adding wine classes to wine data frame

autoplot(wine.pca, data=wine, colour="wine.class", loadings = TRUE, loadings.colour = 'brown',
         loadings.label.colour='brown', loadings.label = TRUE, loadings.label.size = 4,
         loadings.label.repel=TRUE)+stat_ellipse(type = "norm", 
         level=0.68,aes(color=wine.class))

结果图: