setwd("C:/Courses/STA5703/2009-Fall/R/") # --------------------------------------- # PLOTTING CLUSTERING SOLUTIONS WITH MDS # --------------------------------------- data(swiss) dat0 <- na.omit(swiss) mydata <- scale(dat0) # K-Means Clustering with 3 clusters fit <- kmeans(mydata, 3) # Cluster Plot against 1st 2 principal components # vary parameters for most readable graph library(cluster) ?clusplot clusplot(mydata, clus=fit$cluster, color=TRUE, shade=TRUE, labels=2, lines=0) # ....................................................... # Centroid Plot against 1st 2 discriminant functions library(fpc) plotcluster(mydata, fit$cluster) # ....................................................... # Classical/Metric MDS # -------------------- # You can perform a classical MDS using the cmdscale( ) function. # N rows (objects) x p columns (variables) # each row identified by a unique row name d <- dist(mydata) # euclidean distances between the rows fit <- cmdscale(d,eig=TRUE, k=2) # k is the number of dim fit # view results # plot solution x <- fit$points[,1] y <- fit$points[,2] plot(x, y, xlab="Coordinate 1", ylab="Coordinate 2", main="Metric MDS", type="n") text(x, y, labels = row.names(mydata), cex=.7) # Nonmetric MDS # -------------- # Nonmetric MDS is performed using the isoMDS( ) function in the MASS package. # N rows (objects) x p columns (variables) # each row identified by a unique row name library(MASS) d <- dist(mydata) # euclidean distances between the rows fit <- isoMDS(d, k=2) # k is the number of dim fit # view results # plot solution x <- fit$points[,1] y <- fit$points[,2] plot(x, y, xlab="Coordinate 1", ylab="Coordinate 2", main="Nonmetric MDS", type="n") text(x, y, labels = row.names(mydata), cex=.7)