Home > front end >  How to label plot with value of bars?
How to label plot with value of bars?

Time:10-06

I'm trying to make a barplot with two categorical values. barplot of two categorical variables with purple for female and yellow for male

CodePudding user response:

With some sample data from that question you linked you can do it like this:

library(ggplot2)
library(viridis)
#> Loading required package: viridisLite

Fruit <- c(rep("Apple", 3), rep("Orange", 5))
Bug <- c("worm", "spider", "spider", "worm", "worm", "worm", "worm", "spider")

df <- data.frame(Fruit, Bug)

ggplot(df, aes(Fruit, fill = Bug))   geom_bar(position = "dodge")  
  geom_text(
    aes(label = after_stat(count)),
    stat = "count",
    vjust = -0.5,
    position = position_dodge(width = 0.9)
  )  
  geom_text(
    aes(y = after_stat(count), label = Bug),
    stat = "count",
    vjust = -1.5,
    position = position_dodge(width = 0.9)
  )  
  scale_y_continuous(expand = expansion(add = c(0, 1)))  
  scale_fill_viridis(option = "viridis", discrete = TRUE)

A few things to note:

  • geom_bar doesn't need ..count.. passed as a y-value - it defaults to counting
  • after_stat(count) is the updated form of .. notation
  • Text labels need dodges added - default width is 0.9 for bars so this width matches the placement of the bars.

CodePudding user response:

I can't test the process without your input data, but here's something for you to give a try:

  geom_text(stat='count', aes(label=..count..), vjust=-1)
  • Related