2011-07-27 77 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