Guest User

Untitled

a guest
Jul 17th, 2018
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.33 KB | None | 0 0
  1. library(MASS)
  2.  
  3.  
  4. sigma.test<-matrix(c(8,3,5,8),2,2)
  5. biv.norm<-mvrnorm(200,mu=rep(0, 2),Sigma=sigma.test)
  6. biv.pca<-prcomp(biv.norm,center=FALSE)
  7.  
  8. #An array is just a high dimensional matrix. So this is 2x2x50. There is nothing special about the number 50, I just picked that to smooth the
  9. #animation.
  10. #The numbers in the sequence make transition.ar[,,1] the 2x2 identity matrix and transition.ar[,,50] the final transformed rotation matrix from
  11. #the principal components.
  12.  
  13. transition.ar<-array(0,c(2,2,50))
  14. transition.ar[1,1,]<-seq(1,0.7040705,length.out=50)
  15. transition.ar[1,2,]<-seq(0,-0.7101301,length.out=50)
  16. transition.ar[2,1,]<-seq(0,0.7101301,length.out=50)
  17. transition.ar[2,2,]<-seq(1,0.7040705,length.out=50)
  18.  
  19. #Unlike transforming the segments by hand, we can use matrix multiplication to transform the data points.
  20. #pre-multiplying biv.norm by the identity matrix gives you biv.norm again. Pre-multiplying it by the
  21. #rotation matrix gives you the same points arranged on the axes of their variation. We interpolate between
  22. #those two.
  23. ##This part requires that you have Imagemagick installed.
  24. library(animation)
  25. saveMovie({
  26. for (i in 1:50) {
  27. plot(1,xlim=c(-10,10),ylim=c(-10,10),xlab="PC1",ylab="PC2",main="Transition to PCA",type="n")
  28. abline(coef(lm(biv.norm[,2]~biv.norm[,1]))[1],coef(lm(biv.norm[,2]~biv.norm[,1]))[2],col=2,lty=3)
  29. points((biv.norm%*%transition.ar[,,i])[,1],(biv.norm%*%transition.ar[,,i])[,2],pch=20)
  30. abline(coef(lm((biv.norm%*%transition.ar[,,i])[,2]~(biv.norm%*%transition.ar[,,i])[,1]))[1],coef(lm((biv.norm%*%transition.ar[,,i])[,2]~(biv.norm%*%transition.ar[,,i])[,1]))[2],col=2)
  31. Sys.sleep(ani.options("interval"))
  32. }
  33. },interval = 0.03, moviename = "pcaanim.gif",outdir = getwd(), width = 600, height = 600);
  34. #That saves the movie. If you just want to see the plot in R you can type in the console (w/o the comment marks of course!)
  35. #for (i in 1:50) {
  36. # plot(1,xlim=c(-10,10),ylim=c(-10,10),xlab="PC1",ylab="PC2",main="Transition to PCA",type="n")
  37. # abline(coef(lm(biv.norm[,2]~biv.norm[,1]))[1],coef(lm(biv.norm[,2]~biv.norm[,1]))[2],col=2,lty=3)
  38. # points((biv.norm%*%transition.ar[,,i])[,1],(biv.norm%*%transition.ar[,,i])[,2],pch=20)
  39. # abline(coef(lm((biv.norm%*%transition.ar[,,i])[,2]~(biv.norm%*%transition.ar[,,i])[,1]))[1],coef(lm((biv.norm%*%transition.ar[,,i])[,2]~(biv.norm%*%transition.ar[,,i])[,1]))[2],col=2)
  40. # Sys.sleep(0.03)
  41. # }
Add Comment
Please, Sign In to add comment