this is my reproducible example
library(ggplot2)
library(dplyr)
mydf<-data.frame(a = rep(c(1:3), each=2),
b = c(0.5, 0.5, 1, 1, 1.5, 1.5))
mydf %>%
ggplot(aes(x = a)) +
geom_bar(aes(weight=b))
# and this is a variant getting the same result
mydf %>%
ggplot(aes(x = a, weight=b)) +
geom_bar()
Now I want to add the text labels geom_text() with corresponding values (sum of weights) on top of the bars.
The way I would like to achieve that is by labeling the data without creating a new dataframe (and then using geom_col in combination with geom_text()) but instead following the stream of the code drafted above.
It might be a trivial issue but I’m somehow tied in a knot with the idea to follow a sort of afert_stat approach but without getting to any viable solution so far.
I would like to understand how it is possible (and eventually, in fact, if it is!).
>Solution :
You need to use stat = 'count' inside geom_text, and you need to make sure that b is mapped to the weight aesthetic in this layer; either directly or, as in this example, inherited from the main ggplot call to save on typing.
ggplot(mydf, aes(x = a, weight = b)) +
geom_bar() +
geom_text(aes(label = after_stat(count)), stat = 'count', nudge_y = 0.1)
