通过k均值聚类着色ggplot的plotmatrix?

时间:2012-07-16 12:04:08

标签: r ggplot2 k-means

我正在尝试使用ggplot2创建6个数据变量的对图,并根据它们所属的k均值聚类对点进行着色。我阅读了令人印象深刻的'GGally'软件包的文档,以及Adam Laiacano [http://adamlaiacano.tumblr.com/post/13501402316/colored-plotmatrix-in-ggplot2]的非正式修复程序。不幸的是,我找不到任何方法来获得所需的输出。

以下是示例代码: -

#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))

两个图都已创建,但未根据群集进行着色。

希望我在论坛上没有错过这个问题的答案,如果情况确实如此,请道歉。任何帮助都将受到高度赞赏。

谢谢!

1 个答案:

答案 0 :(得分:4)

plotmatrix2的以下略微修改对我来说很好:

plotmatrix2 <- function (data, mapping = aes())
{
    grid <- expand.grid(x = 1:ncol(data), y = 1:ncol(data))
    grid <- subset(grid, x != y)
    all <- do.call("rbind", lapply(1:nrow(grid), function(i) {
        xcol <- grid[i, "x"]
        ycol <- grid[i, "y"]
        data.frame(xvar = names(data)[ycol], yvar = names(data)[xcol], 
            x = data[, xcol], y = data[, ycol], data)
    }))
    all$xvar <- factor(all$xvar, levels = names(data))
    all$yvar <- factor(all$yvar, levels = names(data))
    densities <- do.call("rbind", lapply(1:ncol(data), function(i) {
        data.frame(xvar = names(data)[i], yvar = names(data)[i], 
            x = data[, i])
    }))
    densities$xvar <- factor(densities$xvar, levels = names(data))
    densities$yvar <- factor(densities$yvar, levels = names(data))
    mapping <- defaults(mapping, aes_string(x = "x", y = "y"))
    class(mapping) <- "uneval"
    ggplot(all) + facet_grid(xvar ~ yvar, scales = "free") + 
        geom_point(mapping, na.rm = TRUE) + stat_density(aes(x = x, 
        y = ..scaled.. * diff(range(x)) + min(x)), data = densities, 
        position = "identity", colour = "grey20", geom = "line")
}


plotmatrix2(mtcars[,1:3],aes(colour = factor(cyl)))

enter image description here

这可能是 ggplot2 版本问题,但我不得不强制densities数据框中的分面变量成为因素(即使在 GGally 版本)。另外,通常不会将向量传递给aes(),而只是传递列名。