Home > Software design >  Specify color and shape legend in fviz_pca from the R package FactoExtra
Specify color and shape legend in fviz_pca from the R package FactoExtra

Time:11-03

When having two group variables, for example, the following modified irisdata set (adding a factor variable Site):

SepalLengthCm   SepalWidthCm    PetalLengthCm   PetalWidthCm    Species Site
5.1 3.5 1.4 0.2 Iris-setosa A
4.9 3   1.4 0.2 Iris-setosa A
4.7 3.2 1.3 0.2 Iris-setosa A
4.6 3.1 1.5 0.2 Iris-setosa A
5   3.6 1.4 0.2 Iris-setosa A
5.4 3.9 1.7 0.4 Iris-setosa A
5.2 3.4 1.4 0.2 Iris-setosa A
4.7 3.2 1.6 0.2 Iris-setosa A
4.8 3.1 1.6 0.2 Iris-setosa A
7   3.2 4.7 1.4 Iris-versicolor A
6.4 3.2 4.5 1.5 Iris-versicolor A
6.9 3.1 4.9 1.5 Iris-versicolor A
5.5 2.3 4   1.3 Iris-versicolor A
6.5 2.8 4.6 1.5 Iris-versicolor A
5.7 2.8 4.5 1.3 Iris-versicolor B
6.3 3.3 4.7 1.6 Iris-versicolor B
4.9 2.4 3.3 1   Iris-versicolor B
6.6 2.9 4.6 1.3 Iris-versicolor B
5.2 2.7 3.9 1.4 Iris-versicolor B
6.3 3.3 6   2.5 Iris-virginica  B
5.8 2.7 5.1 1.9 Iris-virginica  B
7.1 3   5.9 2.1 Iris-virginica  B
6.3 2.9 5.6 1.8 Iris-virginica  B
6.5 3   5.8 2.2 Iris-virginica  B
7.6 3   6.6 2.1 Iris-virginica  B
4.9 2.5 4.5 1.7 Iris-virginica  B
7.3 2.9 6.3 1.8 Iris-virginica  B
6.7 2.5 5.8 1.8 Iris-virginica  B
7.2 3.6 6.1 2.5 Iris-virginica  B

I would like to :
1)mapping point color to Iris$Species, and mapping point shape to Iris$site;
2)change the legend title to "color" or "shape".

The codes I'm using:

library(factoextra)

data(Iris)
res.pca <- PCA(Iris[,1:4], graph = F)

fviz_pca_biplot(res.pca,
                #individuals
                geom.ind="point",
                col.ind=Iris$Species,
                pointshape=Iris$Site,
                
                #variables
                col.var="steelblue")

enter image description here It presents an error when I use pointshape=Iris$Site

Error: Aesthetics must be either length 1 or the same as the data (3): shape

1) How should I map the individual points to more than one different group?
2) How to edit the legend title?

CodePudding user response:

Because ggbiplot based on ggplot() object, you may use geom_point to add point and shape manually,

iris.pca <- PCA(iris[,1:4], graph = F)
fviz_pca_biplot(iris.pca,obs.scale = 1, var.scale = 1, alpha=0, col.var="steelblue")   
  geom_point(aes(shape = factor(iris$Site), colour = factor(iris$Species)))  
  guides(shape = guide_legend(title = "shape"),
         colour = guide_legend(title = "color"))

enter image description here

  • Related