Search code examples
rggplot2bar-chartpercentagegeom-bar

Percentage labels are not displayed over bar plot


I am trying to plot a barplot with percentage labels. However, the percentages are annoyingly not displayed above each respective bar, but is rather placed in the way you see below. Anyone know what is causing this and how to fix it?

The code I used is:

p1 <- ggplot(mtcars, aes(x= cyl)) + 
      geom_bar(aes(fill = vs), stat = "count") + 
      geom_text(aes(label = scales::percent(..prop..), y= ..prop..), stat = "count", vjust = -0.5) +  
      theme_classic() + ylab("Count") + facet_grid(vs ~ .)

which gives

Barplot of tcars

Please note that I want to keep count on the y-axis.


Solution

  • We can use ymax and vjust:

    library(ggplot2)
    ggplot(mtcars, aes(x= cyl)) + 
    geom_bar(aes(fill = vs), stat = "count") + 
    geom_text(aes(ymax= ..prop.., label = scales::percent(..prop..)), stat = "count", vjust = -.1) + 
    theme_classic() + 
    ylab("Count") + 
    facet_grid(vs ~ .)
    

    enter image description here