Youtube Channel: https://www.youtube.com/c/TechAnswers88

Video link https://youtu.be/kSTwRbdXfMI

How to use after_stat to access the available stats in your GGPLOT.

Package needed

We only need ggplot2 package. Use the install packages command as shown below in comments if you do not have the package already intalled.

#install.packages("ggplot2")
library(ggplot2)
library(dplyr)
packageVersion("ggplot2")
## [1] '3.5.1'

Data for our plot

We will be using the mpg dataset. We will be using a data field called ‘class’ in the mpg dataset

head(mpg)
## # A tibble: 6 × 11
##   manufacturer model displ  year   cyl trans      drv     cty   hwy fl    class 
##   <chr>        <chr> <dbl> <int> <int> <chr>      <chr> <int> <int> <chr> <chr> 
## 1 audi         a4      1.8  1999     4 auto(l5)   f        18    29 p     compa…
## 2 audi         a4      1.8  1999     4 manual(m5) f        21    29 p     compa…
## 3 audi         a4      2    2008     4 manual(m6) f        20    31 p     compa…
## 4 audi         a4      2    2008     4 auto(av)   f        21    30 p     compa…
## 5 audi         a4      2.8  1999     6 auto(l5)   f        16    26 p     compa…
## 6 audi         a4      2.8  1999     6 manual(m5) f        18    26 p     compa…

Create a basic bar chart using GGPLOT

pl <- ggplot (data = mpg)
pl <- pl + geom_bar(aes(x = class))
pl <- pl + theme_minimal()
pl

Use after_stat to show percentage in the bar chart

after_stat() replaces the old approaches of using either stat() or surrounding the variable names with …

library(scales)
pl <- ggplot (data = mpg, aes(x = class))
pl <- pl + geom_bar()
pl <- pl + geom_text(stat = "count",aes(label = paste0(after_stat(count)
                                                       ," ("
                                                       ,scales::percent(after_stat(count)/ sum(after_stat(count))),")")
                                        , vjust = -0.5
                                        ))
pl <- pl + theme_classic()

pl

What did we use before after_stat came in GGPLOT?

pl <- ggplot (data = mpg)
pl <- pl + geom_bar(aes(x = class, y = (..count..)/sum(..count..)))
pl <- pl + theme_classic()
pl <- pl + scale_y_continuous(labels = percent)
pl

My favourite method to show the count with percentage

mpgCount <- mpg%>%
            dplyr::count(class)%>%
            dplyr::mutate(perc = n/sum(n) * 100)

pl <- ggplot (data = mpgCount, aes(x = class, y = n, fill = class))
pl <- pl + geom_col()
pl <- pl + geom_text(aes(x = class, y = n
                         , label = paste0(n, " (", round(perc,1),"%)")
                         , vjust = -0.5
                         
                         ))
pl <- pl + theme_classic()
pl <- pl + labs(title ="Bar chart showing count and percentage")
pl