rggplot2ggbiplot

Custom legend order ggbiplot, built off ggplot2


I have created a PCA plot in using the ggbiplot() function, form the ggbiplot package, which is built on top of ggplot2. Here is an analogous, reproducible example:

library(ggbiplot)
data(wine)
wine.pca <- prcomp(wine, scale. = TRUE)
print(ggbiplot(wine.pca, obs.scale = 1, var.scale = 1, groups = wine.class, ellipse = TRUE, circle = TRUE))

enter image description here So far so good. I want to change the legend order to grginolino, barbera, barolo (rather than barolo, grignolino, barbera as it is now). The names are stored in the environmental factor variable wine.class.

Apologies for such a simple question, but I cannot find a straight forward answer from the ggplot2 help that generalizes to this case.


Solution

  • You need to reorder wine.class levels; look below:

    library(ggbiplot)
    
    data(wine, package = "ggbiplot")
    wine.pca <- prcomp(wine, scale. = TRUE)
    wine.class.reorder <-  factor(wine.class, levels = c("grignolino", "barbera", "barolo"))
    
    ggbiplot(wine.pca, obs.scale = 1, var.scale = 1, groups = wine.class.reorder, 
                       ellipse = TRUE, circle = TRUE)