Labelling percentage in count bar graph

Hi. I have a bar graph that shows the count of students attending or not attending online class. But I want the percentage to appear as labels. How can I do it?

library(tidyverse)
library(scales)
#> 
#> Attaching package: 'scales'
#> The following object is masked from 'package:purrr':
#> 
#>     discard
#> The following object is masked from 'package:readr':
#> 
#>     col_factor
nit<-tibble::tribble(
  ~online_class,
          "Yes",
          "Yes",
          "Yes",
          "Yes",
          "Yes",
           "No",
          "Yes",
           "No",
          "Yes",
          "Yes",
          "Yes",
           "No"
  )

ggplot(nit,aes(online_class))+
  geom_bar(aes(fill=online_class))+
  geom_text(stat = 'count',aes(label=..count..))


Created on 2022-03-17 by the reprex package (v2.0.1)
1 Like

Here is one solution.

library(tidyverse)
#> Warning: package 'tibble' was built under R version 4.1.2
library(scales)
#> 
#> Attaching package: 'scales'
#> The following object is masked from 'package:purrr':
#> 
#>     discard
#> The following object is masked from 'package:readr':
#> 
#>     col_factor

nit<-tibble::tribble(
  ~online_class,
  "Yes",
  "Yes",
  "Yes",
  "Yes",
  "Yes",
  "No",
  "Yes",
  "No",
  "Yes",
  "Yes",
  "Yes",
  "No"
)

ggplot(nit,aes(online_class))+
  geom_bar(aes(fill=online_class))+
  geom_text(stat = 'count',aes(label=percent(..count../nrow(nit))))

Created on 2022-03-16 by the reprex package (v2.0.1)

Thanks for this. But just for my curiosity, is there any method for doing this using scales package?

Regards,
Nithin

Well, the percent() function I used is from the scales package, so I met that condition in a way. I have rarely used the scales package and it would not surprise me at all if there is a better way to use it in this case. It does seem to be targeted at controlling what is displayed on axes and in legends rather than on text annotations. In fact, the percent function is described as being retired in the documentation and its replacement, label_percent(), does not seem to work within the aes() function because label_percent() returns a labeling function of the type used in scale_* functions.

Thanks a lot..

Regards,
Nithin

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.