1

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?

1 Answer 1

3

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 = after_stat(count)),
           position = position_stack(vjust = 0.5))

enter image description here

EDIT: As per Fkiran comment, in ggplot2 3.4.0 forwards use after_stat(count).

Sign up to request clarification or add additional context in comments.

1 Comment

Instead of aes(label = ..count..) use aes(label = after_stat(count)) as the dot-dot notation (..count..) was deprecated in ggplot2 3.4.0.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.