如何为R包“factoextra”中的“fviz_pca_biplot”中的变量分配颜色?

vuktfyat  于 2023-04-09  发布在  其他
关注(0)|答案(2)|浏览(272)

我试图为PCA双标图中的变量分配不同的颜色。但是,R包factoextra中的fviz_pca_biplot无法为每个变量绘制正确的颜色。

library(factoextra)

data(iris)
res.pca <- prcomp(iris[, -5],  retx = TRUE, center = TRUE, scale. = TRUE)
res.pca

my.col.var <- c("red", "blue", "red", "yellow")

fviz_pca_biplot(res.pca, repel = TRUE, axes = c(1, 2), 
                col.var = my.col.var, col.ind = "#696969", 
                label = "var", title = "")

我已经为变量“Sepal.Length”、“Sepal.Width”、“Petal.Length”和“Petal.Width”指定了“red”、“blue”、“red”、“yellow”。然而,该图显示了所有变量的错误颜色。

ljsrvy3e

ljsrvy3e1#

在函数中,我们必须指定col.var=的变量名称,而不是颜色。然后我们可以手动将颜色赋予palette=选项。因此代码为:

library(factoextra)

data(iris)
res.pca <- prcomp(iris[, -5],  retx = TRUE, center = TRUE, scale. = TRUE)
res.pca
my.col.var <- c("red", "blue", "red", "yellow")

fviz_pca_biplot(res.pca
                , repel = TRUE
                , axes = c(1, 2)
                , col.var = c("Sepal.Length", "Sepal.Width",  "Petal.Length", "Petal.Width" )
                , col.ind = "#696969"
                , label = c("var")
                , title = ""
                , palette = my.col.var
                )

yduiuuwa

yduiuuwa2#

ggbiplot基于ggplot()对象,因此我们可以使用scale_color_manual

library(factoextra)

my.col.var <- c("red", "blue", "red", "yellow")

fviz_pca_biplot(res.pca, repel = TRUE, axes = c(1, 2), 
                col.var = colnames(iris)[1:4], col.ind = "#696969", 
                label = "var", title = "")+
  scale_color_manual(values = my.col.var)

相关问题