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)
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)
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?
brx
is a vector of length 13, not length 1. In any casegeom_histogram
(which uses the same aesthetics asgeom_bar
) does not understandbreaks
as an aesthetic mapping, so even something likeaes(breaks = 1)
would be ignored. – Z.Lin