Home > Software design >  Add total count and precent on top of barplot in ggplot2
Add total count and precent on top of barplot in ggplot2

Time:11-01

I have created the following graph with this code

  geom_bar(colour="black",fill="darkgrey")   theme_apa()   theme(
  plot.title = element_blank(),
  axis.title.x = element_blank(),
  axis.title.y = element_blank()) 
geom_text(stat='count', aes(label=..count..), vjust=-0.5)  
  scale_y_continuous(limits = c(0,25))

enter image description here

  1. First of all, how do I make the scale_y_continuous(limits = c(0,25)) automatically recognize the max count in the graph, and expand the y axis by 3? In this case, I've set it to 25 myself, but is there a way to make it do that automatically (e.g. 22 from the first response 3)?

  2. On top of each bar I have the count of each response. Is there a way to make it show the count, and in brackets the percent of that count compared to the total? E.g the percent of 22 out of the 51 responses in total would look like 22 (43%)

CodePudding user response:

To answer your question point by point.

  1. The limits argument of the scale can take a function (or in recent versions a lambda syntax formula), that takes the natural limits as a length 2 vector as input. You can write your own formula if you want to expand the maximum by 3.
  2. You can use the after_stat() function to access computed variables, so you can format the count computed variable to your liking.
library(ggplot2)

df <- data.frame(
  value = sample(LETTERS[1:5], 50, replace = TRUE)
)

ggplot(df, aes(value))  
  geom_bar()  
  geom_text(
    stat = "count", vjust = -1,
    aes(label = after_stat(
      paste0(count, " (", count * 100 / sum(count), "%)")
    ))
  )  
  scale_y_continuous(
    limits = ~ c(0, .x[2]   3)
  )

Created on 2021-11-01 by the reprex package (v0.3.0)

  • Related