Count labels for the `scale_x_binned` histogram in ggplot 3.3.0

Viewed 608

In version 3.3.0 of ggplot2, we now have the scale_*_binned binning scales. This is useful when creating a more visually appealing histogram

  • How can I add labels on the histogram bars indicating the counts?

What do I put in the labels argument in + geom_text(aes(label = ...))

I have the feeling that the answer is somewhere in the saved objects in the ggplot object p (see below) in the form of a calculated quantity somewhere, but I can't seem to find it.


library(ggplot2)
#> Warning: package 'ggplot2' was built under R version 3.6.3

p <- 
ggplot(mtcars) +
  geom_bar(aes(mpg)) +
  scale_x_binned()

p


names(p)
#> [1] "data"        "layers"      "scales"      "mapping"     "theme"      
#> [6] "coordinates" "facet"       "plot_env"    "labels"

Created on 2020-05-10 by the reprex package (v0.3.0)

1 Answers

The labels for the counts can be added via geom_text(aes(x = mpg, label = ..count..), stat = "count"). Try this

library(ggplot2)

p <- 
  ggplot(mtcars) +
  geom_bar(aes(mpg)) +
  geom_text(aes(x = mpg, label = ..count..), stat = "count", vjust = -.2) +
  scale_x_binned()

p

Created on 2020-05-10 by the reprex package (v0.3.0)

Related