在ggplot2中绘制堆积条上方的和值

swc*_*hen 9 r bar-chart ggplot2

如何在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()
Run Code Online (Sandbox Code Playgroud)

Dav*_*son 23

你可以通过创建每类总数的数据集来做到这一点(这可以通过多种方式完成,但我更喜欢dplyr):

library(dplyr)
totals <- hp %>%
    group_by(class) %>%
    summarize(total = sum(value))
Run Code Online (Sandbox Code Playgroud)

然后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)
Run Code Online (Sandbox Code Playgroud)

您可以使用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)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述


Axe*_*man 17

您可以直接使用内置的汇总功能ggplot2

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

在此处输入图片说明

  • @Matt_B我猜你的意思是“乐趣=总和”? (2认同)