如何在R中绘制kmeans质心的多个条形图

时间:2014-04-25 14:41:54

标签: r cluster-analysis data-visualization k-means bar-chart

我希望从kmeans绘制每个质心的多个条形图。因此,如果我的kmeans输出如下所示:

          Col1        Col2        Col3       Col4        Col5       Col6 id
1  -0.04565042 -0.10418210 -0.11332770  1.8421049 -0.15583161  0.2955061  1
2  -0.02980742 -0.09230721 -0.10254823  0.7768368 -0.13604858 -1.0621160  2
3  -0.03453375  0.03384436 -0.04138790 -0.8173785 -0.04392300  0.8994793  3
4  -0.02597710 -0.07222757 -0.09132922  0.3613666 -0.11597514  0.4206306  4
5   5.56713706 39.99970666  9.59856271 -0.9127473  0.18791485  0.7145491  5
6   0.50077963  1.19455507 22.18617679 -0.4242876 24.71755658 -0.1185781  6
7  64.43412948 25.77130149  8.58296327 -1.0202411  0.22130397 -3.1369832  7
8  -0.03129882 -0.06491623 -0.07644194 -0.7165224 -0.08753829 -0.4597830  8
9   0.44497871  1.49909627  2.92072459 -0.5929353  3.96874222  0.1152115  9
10  0.14930793 -0.01842652 -0.07803882 -0.6001613 -0.10938865 -2.2813694 10

然后我想要10个中心(每行)中的每一个的条形图,其中条形是列特征。如何堆叠这些多个图,使它们显示为一个可视化?

1 个答案:

答案 0 :(得分:1)

这就是你要找的东西:

library(ggplot2)
library(reshape2)

# Create fake data with the same structure as your data frame
set.seed(5)
dat = data.frame(replicate(6, rnorm(10)), 1:10)
names(dat) = c(paste0("Col",1:6),"id")

# Convert data frame from "wide" to "long" format
dat.m = melt(dat, id.var='id')

ggplot(dat.m, aes(x=factor(id), y=value)) + 
  geom_bar(fill=hcl(195, 100, 65)) + 
  xlab("ID") + ylab("Mean") +
  facet_grid(variable ~ .) 

enter image description here