Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Change limits of legend bar using factoextra ggplot2

I’m performing a PCA using R. I’m drawing a biplot of the PC1 and the PC2 using factoextra as in this example.

library(factoextra)

# Load decaathlon2 data
data(decathlon2)
decathlon2.active <- decathlon2[1:23, 1:10]

# PCA
res.pca <- prcomp(decathlon2.active, scale = TRUE)

# Plot
fviz_pca_var(res.pca,
             col.var = "contrib",
             gradient.cols = c("#00AFBB", "#E7B800", "#FC4E07"),
             repel = TRUE)

enter image description here

How can I change the limits of the legend bar? I would like to define the limits between 5 and 10, instead of the current [8.8, 9.4].

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The example you gave does not have the stated range of [8.8, 9.4] – presumably you are referring to a different plot created from your actual data. Setting the color range to [5, 10] in the given example would leave some of the arrows uncolored (since some of the contributions are greater than 10), so let us demonstrate by increasing the scale of the color bar in the example image from [6, 12] to [0, 15].

To do this, you can add a scale_color_gradientn to the plot, specifying your own limits. Use the same colors you passed to gradient.cols:

fviz_pca_var(res.pca, col.var = "contrib", repel = TRUE) +
  scale_color_gradientn(name = "contrib", limits = c(0, 15),
                        colours = c("#00AFBB", "#E7B800", "#FC4E07"))

enter image description here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading