[R] colored PCA biplot

Cuvelier Etienne ecu at info.fundp.ac.be
Wed Apr 29 09:45:31 CEST 2009


Hillary Cooper a écrit :
> Hi-
> I'm trying to make my PCA (princomp) colored. In my csv excel sheet, I have
> the first column numbered according to the groupings I want to assign to the
> PCA. I've played around with trying to set this first column as the color
> vector, but haven't had any luck.
> Any suggestions? Thanks,
> 
> Hillary

Hellor Hillary,
Here is some modifications of my own DIY code,
the thing to do is to test it and compare with the original biplot and 
with what you want.

I hope it helps

Etienne

#my.data is your/my data
# I create some groups just for the  test
groups = sample(1:3,N,replace=TRUE)
N = nrow(my.data)
acp=princomp(my.data,cor=TRUE)
# The original biplot for comparison
biplot(acp)
# Compute de min/max of new coordinates
xmin = min(acp$scores[,1])
xmax = max(acp$scores[,1])
ymin = min(acp$scores[,2])
ymax = max(acp$scores[,2])
plot(c(xmin,xmax),c(ymin,ymax),col="white", xlab="Comp 1", ylab="Comp 2")
# Plot the points with colors
text(acp$scores[,1],acp$scores[,2],1:N,col= groups)
title("PCA with colors")
abline(v=0,lty=2)
abline(h=0, lty=2)
# Compute and apply a re-scaling for the arrows of old components
# xl.min for min of xloadings,...
xl.min = min(0,min(acp$loadings[,1]))
xl.max = max(0,max(acp$loadings[,1]))
yl.min = min(0,min(acp$loadings[,2]))
yl.max = max(0,max(acp$loadings[,2]))
xl.scale = max(abs(xmax),abs(xmin))/max(abs(xl.max),abs(xl.min))*0.75
# 0.75 factor is just for leave some place for the text
yl.scale = max(abs(ymax),abs(ymin))/max(abs(yl.max),abs(yl.min))*0.75
#Draw old components
arrows(rep(0,100),rep(0,100),acp$loadings[,1]*xl.scale, 
acp$loadings[,2]*yl.scale)
# Names of old components
text(acp$loadings[,1]*xl.scale*1.25, acp$loadings[,2]*yl.scale*1.25 
,colnames(my.data))

> 
> 	[[alternative HTML version deleted]]
> 
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>




More information about the R-help mailing list