2015-06-05 35 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

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

相关问题