在ggplot2中,如何在堆积条形图上方绘制总值

23

如何在ggplot2中绘制每个类的总和值(在我的情况下:a=450,b=150,c=290,d=90)在堆叠条形图上方?这是我的代码:

#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()

1
数据中有一个名为“amount”的列,但在美学上却是“-value”;这两者应该不一致吧? - David Robinson
确实。我尝试编辑以修复示例,但编辑被拒绝了... aes 调用应该是:aes(x=reorder(class,-amount,sum),y=amount,label=amount,fill=year)+ - Keith Hughitt
非常相关 - Axeman
2个回答

39

你可以直接使用 ggplot2 的内置摘要功能:

ggplot(hp, aes(reorder(class, -amount, sum), amount, fill = year)) +
  geom_col() +
  geom_text(
    aes(label = after_stat(y), group = class), 
    stat = 'summary', fun = sum, vjust = -1
  )

在这里输入图片描述


1
我需要将 fun.y = sum 更改为 fun.y = sum 才能使之工作。 - Matt_B
2
@Matt_B 我猜你是指 fun = sum 吗? - Axeman

35
你可以通过创建每个类别总数的数据集来实现这一点(可以用多种方式完成,但我更喜欢使用 dplyr):
library(dplyr)
totals <- hp %>%
    group_by(class) %>%
    summarize(total = sum(value))

然后在您的图表中添加一个geom_text层,使用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


我们如何在条形图中为每年增加价值? - Mostafa90
@Mostafa 请访问此链接 - UseR10085

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接