gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 13:34:42 26 4
gpt4 key购买 nike

如何在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()

最佳答案

您可以直接使用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
)

enter image description here

关于r - 在 ggplot2 中的堆积条上方绘制总和值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30656846/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com