我正在嘗試使用ggplot2創建一個包含6個數據變量的對圖,並根據它們所屬的k-均值聚類對這些點進行着色。我閱讀了令人印象深刻的「GGally」套裝的文檔以及Adam Laiacano的非正式修復[http://adamlaiacano.tumblr.com/post/13501402316/colored-plotmatrix-in-ggplot2]。不幸的是,我找不到任何方法來獲得所需的輸出。k-means集羣着色ggplot的plotmatrix?
下面是一個示例代碼: -
#The Swiss fertility dataset has been used here
data_ <- read.csv("/home/tejaskale/Ubuntu\ One/IUCAA/Datasets/swiss.csv", header=TRUE)
data_ <- na.omit(data_)
u <- c(2, 3, 4, 5, 6, 7)
x <- data_[,u]
k <- 3
maxIterations <- 100
noOfStarts <- 100
filename <- 'swiss.csv'
library(ggplot2)
library(gridExtra)
library(GGally)
kmeansOutput <- kmeans(x, k, maxIterations, noOfStarts)
xNew <- cbind(x[,1:6], as.factor(kmeansOutput$cluster))
names(xNew)[7] <- 'cluster'
kmeansPlot <- ggpairs(xNew[,1:6], color=xNew$cluster)
OR
kmeansPlot <- plotmatrix(xNew[,1:6], mapping=aes(colour=xNew$cluster))
兩個圖的創建,但根據簇不着色。
希望我沒有錯過在論壇上回答這個問題,並且如果確實如此,我表示歉意。任何幫助將不勝感激。
謝謝!
你可以用普通的plot命令來做到這一點,也可以在'col'參數中傳遞clusterID。 – 2012-07-16 12:38:54
謝謝你的回答,@ThomasJungblut。但我不確定我完全理解它。你是否建議使用方面?我嘗試使用http://stackoverflow.com/questions/1313954/plotting-two-vectors-of-data-on-a-ggplot2-scatter-plot-using-r上的示例來玩facet_grid。儘管他們沒有達到我的目的。一個最小的例子會對我更好地理解你的建議有巨大的幫助。再次感謝! – 2012-07-16 13:36:27
這只是一個正常的散點圖,其中的點由集羣着色。查看正常的kmeans文檔:http://stat.ethz.ch/R-manual/R-devel/library/stats/html/kmeans.html在底部:'plot(x,col = cl $ cluster) 'cl $ cluster'是分配給集羣的地方。 – 2012-07-16 13:38:12