【问题标题】:How to add y value average text to geom_bar?如何将y值平均文本添加到geom_bar?
【发布时间】:2022-12-19 00:57:48
【问题描述】:
ggplot(aes(x=MALE, y=AMOUNT, fill=MALE)) + geom_bar(stat="summary", fun="mean") +
ylab("Avg Amount") + theme(axis.title.x = element_blank())
鉴于我在创建图表时已经创建了 stat='summary' & fun='mean' ,如何将 y 值添加到条形图的顶部?
【问题讨论】:
标签:
r
ggplot2
mean
geom-text
【解决方案1】:
要在栏顶部添加 y 值作为标签,您可以执行以下操作:
geom_text(aes(label = after_stat(y)), stat = "summary", fun = "mean", vjust = -.1)
使用 mtcars 作为示例数据和一些额外的标签格式:
library(ggplot2)
ggplot(mtcars, aes(x = factor(cyl), y = mpg, fill = factor(cyl))) +
geom_bar(stat = "summary", fun = "mean") +
geom_text(aes(label = after_stat(sprintf("%.1f", y))), stat = "summary", fun = "mean", vjust = -.1) +
ylab("Avg Amount") +
theme(axis.title.x = element_blank())