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