How can I use geom_text
to add percentage labels on top of each bar in ggplot2
? I know there are several similar questions which are already answered. But they either use only 1 categorical variable or compute the percentages before plotting.
I have following plot:
ggplot(data = mtcars)+
geom_bar(aes(x = factor(cyl),
y = (..count..)/sum(..count..)*100,
fill = factor(gear)),
position = "dodge")
Now I want to add the percentage labels on the top. If I use y = (..count..)/sum(..count..)*100
in geom_text
, it says Error in eval(expr, envir, enclos) : object 'count' not found
.
It's easiest to calculate the quantities you need beforehand, outside of ggplot, as it's hard to track what ggplot calculates and where those quantities are stored and available.
First, summarize your data:
Save that if you like, or pipe directly into ggplot:
If you really want to keep it all internal to ggplot, you can use
geom_text
withstat = 'count'
(orstat_count
withgeom = "text"
, if you prefer):which plots exactly the same thing.