This is a test version of Biostars. For the public version, visit https://www.biostars.org.
Putting colors of different samples on PCA plot

"Hi folks,

I have a dataset consisting of 6 different samples. I have created a PCA plot displaying these samples (see Image 1). However, I am unable to assign the same color to replicates originating from the same sample. Additionally, I would like to encircle all the replicates within the plot. Could you please assist me in implementing these modifications to my PCA plot?"

The script I have used is below-

data <- read.csv("normalized_file.csv", row.names = 1)
data <- t(data)

library (FactoMineR)
CA(na.omit(data))

library(factoextra)
library(ggplot2)
summary(data)
res.pca <- PCA(data, scale.unit=TRUE, graph=F)

#to get barplot of eigenvalues
eigenvalues <- res.pca$eig
barplot(eigenvalues[, 2], 
        names.arg=1:nrow(eigenvalues), 
        main = "Variances",
        xlab = "Principal Components",
        ylab = "Percentage of variances",
        col ="steelblue")

# Add connected line segments to the plot
lines(x = 1:nrow(eigenvalues), eigenvalues[, 2], 
      type="b", pch=19, col = "red")    

head(eigenvalues)

# Drawing PCA graphs
plot.PCA(res.pca,axes = c(1, 2), choice = "var", xlab="dim1", ylab="dim2")
plot.PCA(res.pca,axes = c(1, 2), choice = "ind", xlab="dim1", ylab="dim2")

I have included the PCA plot in the image.

enter image description here

pca

1 answer

The variable col.hab is used within plot.PCA to assign colours.

A PCA is just a type of scatter plot, so I would suggest learning how to use the library ggplot2, it's easy to learn, intuitive, and very flexible. Here is a website with a lot of good examples of a lot of different plot types both in base R and in ggplot2. The source code for the plot.PCA shows it's just a ggplot2 wrapper.

Drawing circles around groups can use added by using the stat_ellipse function in ggplot2.

Hi,

Thank you for your suggestion! I will try to follow that and will update here if I succeed. :)

Log in to answer this question.