Search code examples
rpca

Create a 3D pca using Kmean with points labelled


I want to make the plot given below on mtcars dataset.enter image description here.

For doing this I tried the code given here as follows:

require(rgl)
require(SciViews)
require(plotrix)
library(corrplot)
require(ggplot2)
require(reshape)
require("gridExtra")
cars.pca <- pcomp(~mpg+cyl+disp+hp+drat+wt+qsec, data = mtcars)#,  subset = -(8:14))
mtcars_pca = cbind(cbind(mtcars, cars.pca$scores), car = rownames(mtcars))
plot(cars.pca, which = "correlations") 
plot(cars.pca, which = "scores", cex = 0.8) 

The code works fine until here and produces two plot as shown below: plot1 plot2

Using the code given below the plot was made but there was problems in plot:

k <- kmeans(mtcars, 5, nstart=25, iter.max=1000)
new = cbind(mtcars_pca,cluster = k$cluster)
with(new,plot3d(PC1,PC2,PC3, col=k$cluster, size=2, type='s'))
car= = rownames(mtcars)
with(new,text3d(PC1,PC2,PC3,car))

plot4

The scale is not right,it is overlapping as shown in the plot the scale for pc1 has moved above and similarly pc2 and pc3 are overlapping,how these problems can be removed so that scale for pc1,pc2 and pc3 gets printed on right place?


Solution

  • May be you want to play with the parameters aspect, adjust, cex or use jitter to find values that minimize text overlap:

    with(new,plot3d(PC1,PC2,PC3, col=k$cluster, size=2, type='s', aspect=c(3,1,3)))
    car= rownames(mtcars)
    with(new,text3d(jitter(PC1),jitter(PC2),jitter(PC3),car,cex=0.7, adjust=c(0.5,0.9)))
    

    enter image description here