I have a dataset which looks like this:
Smoking population
1 yes group1
2 yes group3
3 yes group2
4 no group1
5 no group1
6 yes group3
7 no group2
8 yes group2
9 yes group3
10 no group1
11 no group1
12 no group3
13 yes group2
14 no group2
15 no group1
16 yes group1
17 yes group2
18 no group3
19 no group3
20 yes group1
21 no group3
I am trying to plot population on the x axis and count on the y axis for yes and no like this:
library(tidyverse)
df %>%
ggplot(aes(x = population , color = Smoking, fill = Smoking)) +
geom_bar(position = 'dodge')+
theme(axis.text.x = element_text(angle=90, vjust=.5, hjust=1))
I need to add the count at the top of the bars. How can I do that?
This changed in ggplot 3.4.0
(November 2022). If you search for questions on this you'll see a lot of code that uses either stat()
or ..count..
.
However, this was deprecated in 3.4.0
. You can now use after_stat(count)
to calculate the counts:
ggplot(df, aes(x = population, color = Smoking, fill = Smoking)) +
geom_bar(position = "dodge") +
theme(axis.text.x = element_text(angle = 90, vjust = .5, hjust = 1)) +
geom_text(
stat = "count",
aes(
label = after_stat(count)
),
position = position_dodge(),
color = "black",
size = 8,
vjust = -0.2
)