在ggplot2中绘制堆积条上方的总和值 [英] draw the sum value above the stacked bar in ggplot2
本文介绍了在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()
解决方案
<您可以通过创建每类总计的数据集来实现此目的(这可以通过多种方式完成,但我更喜欢
library(dplyr)
totals< - hp%> %
group_by(class)%>%
summary(total = sum(value))
然后使用 totals
作为数据集,将<
p + geom_bar(binwidth = 0.5,stat =identity)+
aes(x = reorder(class, - 值),y = value,label = value,fill = year)+
theme()+
geom_text(aes(class,total,label = total,fill = NULL),data = totals )
您可以使用<$ c $使文字高于或低于条的顶部c> 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)
How do I draw the sum value of each class (in my case: a=450, b=150, c=290, d=90) above the stacked bar in ggplot2? Here is my code:
#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()
解决方案
You can do this by creating a dataset of per-class totals (this can be done multiple ways but I prefer dplyr):
library(dplyr)
totals <- hp %>%
group_by(class) %>%
summarize(total = sum(value))
Then adding a geom_text
layer to your plot, using totals
as the dataset:
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)
You can make the text higher or lower than the top of the bars using the vjust
argument, or just by adding some value to 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)
这篇关于在ggplot2中绘制堆积条上方的总和值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文