David Morrisroe
David Morrisroe

Reputation: 11

Labels/points colored by category with PCA

I'm using prcomp to do PCA analysis in R, I want to plot my PC1 vs PC2 with different color text labels for each of the two categories, I do the plot with:

plot(pca$x, main = "PC1 Vs PC2", xlim=c(-120,+120), ylim = c(-70,50))

then to draw in all the text with the different colors I've tried:

text(pca$x[,1][1:18],  pca$[,1][1:18],  labels=rownames(cava), col="green", 
     adj=c(0.3,-0.5))
text(pca$x[,1][19:35], pca$[,1][19:35], labels=rownames(cava), col="red", 
     adj=c(0.3,-0.5))

But R seams to plot 2 numbers over each other instead of one, the pcs$x[,1][1:18] plots the correct points I know because if I use that plot the points it works and produces the same plot as plot(pca$x).

It would be great if any could help to plot the labels for the two categories or even plot the points different color to make it easy to differentiate between the plots easily.

Upvotes: 1

Views: 1861

Answers (1)

Bryan Hanson
Bryan Hanson

Reputation: 6213

You need to specify your x and y coordinates a bit differently:

text(pca$x[1:18,1], pca$x[1:18,2] ...)

This means take the first 18 rows and the first column (which is PC1) for the x coord, etc. I'm surprised what you did doesn't throw an error.

If you want the points themselves colored, you can do it this way:

plot(pca$x, main = "PC1 Vs PC2", col = c(rep("green", 18), rep("red", 18)))

Upvotes: 2

Related Questions