R Biplot以簇为颜色

时间:2015-06-17 12:25:34

标签: r ggplot2 pca

我正在进行PCA转换后的聚类,我想在PCA空间的前两个或三个维度中显示聚类的结果,以及从原始轴到投影的PCA的贡献。

我使用的是使用ggplot的factoextra库,它运行正常,但是我想关掉传说

我的代码:

# Load iris dataset
data(iris)

# PCA
pca <- prcomp(iris[,-5], scale=TRUE)
df.pca <- pca$x

# Cluster over the three first PCA dimensions
kc <- kmeans(df.pca[,1:3], 5)

# 2-D biplot (how to get rid of legend?)
# install.packages("devtools")
# library("devtools")
# install_github("kassambara/factoextra")
library(factoextra)
fviz_pca_biplot(pca, label="var", habillage=as.factor(kc$cluster)) +
  labs(color=NULL) + ggtitle("") +
  theme(text = element_text(size = 15),
      panel.background = element_blank(), 
      panel.grid.major = element_blank(),
      panel.grid.minor = element_blank(),
      axis.line = element_line(colour = "black"),
      legend.key = element_rect(fill = "white"))

enter image description here

如何删除右边的图例列?

不使用任何库的等效双标图也是一个受欢迎的解决方案。

PS:

即使在三维中也很难得到一个好的双标图:

library(rgl)
text3d(pca$x[,1:3],texts=rep("*",dim(pca$x)[1]), col=kc$cluster) # points
text3d(1*pca$rotation[,1:3], texts=rownames(pca$rotation), col="red") # arrows title
coords <- NULL
for (i in 1:nrow(pca$rotation)) {
  coords <- rbind(coords, rbind(c(0,0,0),1*pca$rotation[i,1:3]))
}
lines3d(coords, col="blue", lwd=1)

2 个答案:

答案 0 :(得分:5)

我认为你应该尝试theme(legend.position="none")

 library(factoextra)
 plot(fviz_pca_biplot(pca, label="var", 
  habillage=as.factor(kc$cluster)) + ggtitle("") +
  theme(text = element_text(size = 15), 
      panel.background = element_blank(), 
      panel.grid.major = element_blank(), 
      panel.grid.minor = element_blank(), 
      axis.line = element_line(colour = "black"),
      legend.position="none"))

这就是我得到的:enter image description here

答案 1 :(得分:1)

这也应该有效: 在+ guides(shape=FALSE, color=FALSE)

之后添加ggtitle("")
library(factoextra)
fviz_pca_biplot(pca, label="var", habillage=as.factor(kc$cluster)) +
  labs(color=NULL) + 
  ggtitle("") + guides(shape=FALSE, color=FALSE)
theme(text = element_text(size = 15),
      panel.background = element_blank(), 
      panel.grid.major = element_blank(),
      panel.grid.minor = element_blank(),
      axis.line = element_line(colour = "black"))