我正在尝试使用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