Search code examples
rbar-chartfrequencygeom-text

Grouped bar plot with frequency numbers in a R function


I want to make a function which would plot a bar chart of a certain variable in a database, grouped by participants' sex. I found a way to do this with a chart that displays proportions:

library(ggplot2)
datab <- data.frame(
  value=sample(c(1,2,3,4,5), 50, replace = TRUE),
  value2=sample(c(1,2,3,4,5), 50, replace = TRUE),
  Sex=factor(x=rep(c(1,1,1,0,0),10), labels=c("M","F"))
)


graph_percentages <- function(varijabla){
  ggplot(datab, aes(x= datab[[varijabla]], y=stat(prop), fill=Sex, group=Sex)) +
    geom_bar(position = "dodge", color= "black") +
    geom_text(position = position_dodge(1), size = 2.3, aes(label= scales::percent(..prop..), y= ..prop..), stat="count", vjust = -0.5)+
    xlab(colnames(datab[,varijabla]))  + ylab(NULL)
}

graph_percentages("value")

However, I'm stumped as how to make a similar function that would show frequencies instead of proportions. The main problem is that in "geom_text" I cannot change the "y=" to display frequencies. At least I have not found how.


Solution

  • stat(count) maybe what you are looking for?

    ggplot(datab, aes(x= datab[[varijabla]], y=stat(count), fill=Sex, group=Sex)) +
      geom_bar(position = "dodge", color= "black") +
      geom_text(position = position_dodge(1), size = 2.3, aes(label= ..count.., y= ..count..), stat="count", vjust = -0.5)+
      xlab(colnames(datab[,varijabla]))  + ylab(NULL)
    

    And to keep with the updated syntax, you could replace ..count.. with stat(count) also in your call to geom_text(), i.e:

    geom_text(position = position_dodge(1), size = 2.3, aes(label= stat(count), y= stat(count)), stat="count", vjust = -0.5)