2015-06-05 39 views
5

如何繪製ggplot2中堆積條上方每個類的總和值(在我的情況下:a = 450,b = 150,c = 290,d = 90) ?這裏是我的代碼:在ggplot2中繪製堆積條上方的總和值

library(dplyr) 
totals <- hp %>% 
    group_by(class) %>% 
    summarize(total = sum(value)) 

然後加入geom_text

#Data 
hp=read.csv(textConnection(
"class,year,amount 
a,99,100 
a,100,200 
a,101,150 
b,100,50 
b,101,100 
c,102,70 
c,102,80 
c,103,90 
c,104,50 
d,102,90")) 
hp$year=as.factor(hp$year) 

#Plotting 
p=ggplot(data=hp) 
p+geom_bar(binwidth=0.5,stat="identity")+ 
aes(x=reorder(class,-value,sum),y=value,label=value,fill=year)+ 
theme() 
+0

你有一個字段'數量「,而美學中的」價值「;不應該一樣嗎? –

+0

確實。我嘗試編輯以修正該示例,但編輯被拒絕... 'aes'調用應該是:'aes(x = reorder(class,-amount,sum),y = amount,label = amount,fill =年)+' –

回答

10

您可以通過創建每類總數的數據集(這是可以做到多種方式,但我更喜歡dplyr)做到這一點層到您的情節,使用totals作爲數據集:

p + geom_bar(binwidth = 0.5, stat="identity") + 
    aes(x = reorder(class, -value, sum), y = value, label = value, fill = year) + 
    theme() + 
    geom_text(aes(class, total, label = total, fill = NULL), data = totals) 

可以使文本高於或低於使用vjust參數條的頂部,或者只是添加一些價值total

p + geom_bar(binwidth = 0.5, stat = "identity") + 
    aes(x = reorder(class, -value, sum), y = value, label = value, fill = year) + 
    theme() + 
    geom_text(aes(class, total + 20, label = total, fill = NULL), data = totals) 

enter image description here

+0

我們如何才能在酒吧增加每年的價值? –

相關問題