Reputation: 47
I have a problem that was probaly already asked many times. However, I could not find any solution that helped me. I would like to have the values of the individual bars displayed in the center of each bar. My code is following
geom_bar(aes(x=Fläche, y=Bestäuberarten, fill=Fläche),
stat = "summary", fun = "mean")+
scale_fill_manual(values = c("Brachfläche" = "#E74C3C", "Gestaltete Natur" = "#DAF7A6", "Trockenrasen" = "#F7DC6F"))+
theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
panel.background = element_blank(), axis.line = element_line(colour = "black"),
text = element_text(size=12), legend.position="none", legend.title = element_blank())+
labs(x =element_blank(), y = "Ø-Anzahl Bestäuber")
Would be happy about any help. I guess it has something to do with my aes and the stat="summary" part, but I tried many solutions but nothing worked.
Thank you!
Upvotes: 0
Views: 895
Reputation: 37933
There are 'computed variables' documented in every stat_*()
function that you can use in combination with after_stat()
or stage()
to access these. In the example below, we're stage()
ing to let the y-value initially be mpg
, but halving it after the summary has been computed. Likewise, we're using after_stat()
for the label to be the summarised y-value.
library(ggplot2)
ggplot(mtcars, aes(factor(cyl), mpg)) +
geom_bar(stat = "summary", fun = "mean") +
geom_text(stat = "summary", fun = "mean",
aes(y = stage(mpg, after_stat = y / 2),
label = after_stat(y)))
Created on 2021-07-09 by the reprex package (v1.0.0)
If you're finding that you're using the same statistic in a bunch of layers, it might be more convenient to precompute the statistic.
Upvotes: 1