0
votes

Histogram breaks

In base plot, when you use the hist function, it automatically calculates the breaks using the nclass.Sturges function, in ggplot however, you have to provide the breaks.

If I plot a histogram of the classical faithfull data I get the following graph:

data("faithful")
hist(faithful$waiting)

enter image description here

This works

I found out in this question, that you can mimic the

library(tidyverse)
data("faithful")
brx <- pretty(range(faithful$waiting), n = nclass.Sturges(faithful$waiting), min.n = 1)
ggplot(faithful, aes(waiting)) + 
  geom_histogram(color="darkgray", fill="white", breaks=brx)

enter image description here

But this does not

But I would like to add the breaks within my ggplot function, so I tried this:

ggplot(faithful, aes(waiting)) + 
  geom_histogram(color="darkgray", fill="white", 
                 aes(breaks=pretty(range(waiting), 
                                   n = nclass.Sturges(waiting), 
                                   min.n = 1)))

Which gives me the following error:

Warning: Ignoring unknown aesthetics: breaks
Error: Aesthetics must be either length 1 or the same as the data (272): breaks, x

I understand what it means, but I can put Aesthetics of length one in aes, such as:

ggplot(faithful, aes(waiting)) + 
  geom_histogram(color="darkgray", fill="white", breaks=brx, 
                 aes(alpha = 0.5))

What am I doing wrong?

1
Based on your data, brx is a vector of length 13, not length 1. In any case geom_histogram (which uses the same aesthetics as geom_bar) does not understand breaks as an aesthetic mapping, so even something like aes(breaks = 1) would be ignored.Z.Lin

1 Answers

1
votes

geom_histogram uses the same aes as geom_bar according to the documentation and breaks isn't one of those aesthetics. (See geom_bar)

In the working code chunk you pass breaks to the function geom_histogram directly and that works, but in the problematic chunk you pass it as an aesthetic, and ggplot complains.

This works for me and I think does what you want:

ggplot(faithful, aes(x = waiting)) + 
geom_histogram(color = "darkgray", fill = "white", 
             breaks = pretty(range(faithful$waiting), 
                               n = nclass.Sturges(faithful$waiting), 
                               min.n = 1))