2011-07-27 79 views
8

我一直在浏览this页面上提供的示例,但出于某种原因无法找到正确的方法来完成此操作。如何用ggplot绘制一个堆叠的酒吧?

我有一些数据是这样的:

 Group Member Percentage 
[1,] "1" "A" "60"  
[2,] "1" "A" "20"  
[3,] "1" "A" "20"  
[4,] "1" "B" "80"  
[5,] "1" "B" "5"  
[6,] "1" "B" "5"  
[7,] "1" "B" "5"  
[8,] "2" "C" "50"  
[9,] "2" "C" "50"  
[10,] "2" "D" "25"  
[11,] "2" "D" "25"  
[12,] "2" "D" "25"  
[13,] "2" "D" "20"  
[14,] "2" "D" "5" 

,可以用下面的命令来创建:

a = c(1,1,1,1,1,1,1,2,2,2,2,2,2,2) 
b = c("A","A","A","B","B","B","B","C","C","D","D","D","D","D") 
c = c(60,20,20,80,5,5,5,50,50,25,25,25,20,5) 
dat = data.frame(Group=a, Member=b, Percentage=c) 
ggplot(dat, aes(x=Member, y=Percentage)) + geom_bar(stat="identity", position="dodge", fill="white", colour="black") 

最后一行给我下面的情节:

enter image description here

我真正想要的是连接每个一组中的酒吧到一个酒吧,并将百分比表示为同一酒吧的分数(每个酒吧中的每个酒吧用一个酒吧绘制,每个酒吧以百分比作为他们的颜色)。所以我用下面的:

ggplot(dat, aes(x=Member, y=Percentage)) + geom_bar(stat="identity", colour="white") 

并获得这样的:

enter image description here

但现在我无法得到正确的颜色。我想要的东西完全像下面给出的东西,但我无法理解如何做到这一点。有关如何做到这一点的任何建议?

enter image description here

+1

http://had.co.nz/ggplot2/position_stack.html –

+0

@ GSK3:只要设法做到这一点后,一些试验,虽然我没有用'位置= “堆叠”'。我不知道有什么区别。最好的办法是限制ggplot使用有限的颜色,而不是每找到一个新的百分比使用ggplot。 – Legend

回答

9

好吧终于搞定了!欢呼!下面是完整的代码,如果有人有兴趣:(!非常感谢)

a = c(1,1,1,1,1,1,1,2,2,2,2,2,2,2) 
b = c("A","A","A","B","B","B","B","C","C","D","D","D","D","D") 
c = c(60,20,20,80,5,5,5,50,50,25,25,25,20,5) 
dat = data.frame(Group=a, Member=b, Percentage=c) 
ggplot(dat, aes(x=Member, y=Percentage, fill=Percentage)) + geom_bar(stat="identity", colour="white") 

enter image description here

以怎样被@joran提出的意见:

ggplot(dat, aes(x=Member, y=Percentage, fill=Percentage)) + geom_bar(stat="identity", colour="white") 

enter image description here

+2

干得好!我正准备发布这个......请注意,如果你想要百分比上的离散色彩比例,而不是连续色彩比例,只需使用'fill = factor(Percentage)'。 – joran

+0

+1哦,太棒了!我正在寻找这个版本!尽管如此,我可以取消更好的配色方案。需要进一步探讨这一点。 – Legend

+0

作为一个微不相关的问题,你会碰巧知道如何将图例中的“因素(百分比)”文本更改为其他任何机会的权利? – Legend

4

你很近。尝试

ggplot(dat, aes(x=Member, y=Percentage, fill = factor(Percentage))) + geom_bar(stat = "identity") 

将会产生

enter image description here

+0

+1谢谢!刚刚更新了我的答案@ joran的评论。我想稍微调整一下,这些图表看起来很棒。 – Legend