Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

plotting counts on top of the bars in ggplot2

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))

enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I need to add the count at the top of the bars. How can I do that?

>Solution :

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 = ..count..
        ),
        position = position_dodge(),
        color = "black",
        size = 8,
        vjust = -0.2
    )

enter image description here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading