ggplot2geom-histogram

Adding stat = count on top of histogram in ggplot


I've seen some other examples (especially using geom_col() and stat_bin()) to add frequency or count numbers on top of bars. I'm trying to get this to work with geom_histogram() where I have a discrete (string), not continuous, x variable.

library(tidyverse)

d <- cars |> 
  mutate( discrete_var = factor(speed))

ggplot(d, aes(x = discrete_var)) + 
  geom_histogram(stat = "count") +
  stat_bin(binwidth=1, geom='text', color='white', aes(label=..count..),
           position=position_stack(vjust = 0.5)) +

Gives me an error because StatBin requires a continuous x variable. Any quick fix ideas?


Solution

  • The error message gives you the answer: ! StatBin requires a continuous x variable: the x variable is discrete.Perhaps you want stat="count"?

    So instead of stat_bin() use stat_count()

    And for further reference here is a reproducible example:

    library(tidyverse)
    
    d <- cars |> 
      mutate( discrete_var = factor(speed))
    
    ggplot(data = d, 
           aes(x = discrete_var)) + 
      geom_histogram(stat = "count") +
      stat_count(binwidth = 1, 
                 geom = 'text', 
                 color = 'white', 
                 aes(label = ..count..),
               position = position_stack(vjust = 0.5))
    

    enter image description here