How to Plot Histograms in R Using ggplot2 and Base R
You can plot histograms in R to display the distribution of a continuous variable by grouping data into bins. Use ggplot2 for flexible, publication-ready output or base R hist() for quick exploration and diagnostic checks. Both approaches control the same fundamental parameter: bin width.
library(ggplot2)
ggplot(mtcars, aes(x = mpg)) +
geom_histogram(bins = 10, fill = "steelblue", color = "white")
Set bins to control the number of bars or use binwidth to set a fixed bar width in data units. Add a density curve overlay with after_stat(density) and geom_density(). Use position = "dodge" inside geom_histogram() to display separate bars per group, and facet_wrap() for multi-panel histograms.
ggplot(mtcars, aes(x = mpg, y = after_stat(density))) +
geom_histogram(bins = 10, fill = "lightgray", color = "black") +
geom_density(color = "red", linewidth = 1)
For a quick base R histogram, hist(mtcars$mpg, breaks = "FD", col = "lightblue") applies the Freedman-Diaconis bin-width rule automatically. Pass probability = TRUE to show density instead of counts and overlay a kernel density estimate with lines(density(x)). Bin width is the single most important histogram parameter—too few bins hide the shape, too many create noise. For grouped data, hist() lacks a built-in facet equivalent, so switching to ggplot2 is the cleaner path when you need panel plots.
See also
- Introduction to ggplot2, Getting started with ggplot2
- Base R Graphics and Plotting, Overview of base R plotting
- Data Visualization Best Practices in R, Tips for effective visualizations