2.4 Creating a Histogram
2.4.2 Solution
To make a histogram (Figure 2.8), use hist()
and pass it a vector of values:
hist(mtcars$mpg)
# Specify approximate number of bins with breaks
hist(mtcars$mpg, breaks = 10)
With the ggplot2, you can get a similar result using geom_histogram()
(Figure 2.9):
library(ggplot2)
ggplot(mtcars, aes(x = mpg)) +
geom_histogram()
#> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
# With wider bins
ggplot(mtcars, aes(x = mpg)) +
geom_histogram(binwidth = 4)
When you create a histogram without specifying the bin width, ggplot()
prints out a message telling you that it’s defaulting to 30 bins, and to pick a better bin width. This is because it’s important to explore your data using different bin widths; the default of 30 may or may not show you something useful about your data.