ggplot2 Histogram in R: A Complete Guide to geom_histogram()
A histogram is one of the most useful graphs for exploring a numeric variable. This complete ggplot2 histogram tutorial explains how to build and interpret histograms in R, choose an appropriate binwidth, compare distributions, overlay density curves and avoid common mistakes.
This lesson is part of the ggplot2 tutorial. The first examples use mpg, a dataset supplied with ggplot2. Later examples use downloadable practice CSV files included with this lesson.
1. What does a histogram show?
A histogram displays the distribution of a continuous numerical variable. It divides the variable's range into adjacent intervals, called bins, and counts how many observations fall into each interval. Unlike a categorical bar chart, histogram bars normally touch because the intervals represent a continuous scale.
Use a histogram to investigate the centre, spread, shape, skewness, possible clusters and unusual values in data. It is a useful first step before calculating summary statistics or fitting a statistical model.

- Centre: where values tend to cluster.
- Spread: how widely observations are distributed.
- Shape: whether the distribution is symmetric, skewed, uniform or multimodal.
- Unusual observations: isolated bars or long tails may suggest potential outliers.
2. Create a basic histogram with geom_histogram()
The mpg dataset contains fuel-economy information about cars. Its hwy variable records highway fuel economy in miles per gallon. Load ggplot2, map hwy to the x-axis and add geom_histogram().
install.packages("ggplot2") # Run once if required
library(ggplot2)
ggplot(data = mpg, aes(x = hwy)) +
geom_histogram()
ggplot2 chooses a default number of bins if you do not specify one. It also displays a message recommending that you consider an appropriate binwidth. For a finished analysis, choose and report a binning rule that makes sense for your data.

3. Choose bins and binwidth
The two most common controls are binwidth and bins. They control how finely the numeric range is divided.
Set binwidth
binwidth gives the width of each interval in the original measurement units. For highway fuel economy, a binwidth of 3 groups values into intervals three miles per gallon wide.
ggplot(mpg, aes(x = hwy)) +
geom_histogram(
binwidth = 3,
fill = "steelblue",
colour = "white"
) +
labs(
title = "Highway fuel economy",
x = "Highway miles per gallon",
y = "Number of cars"
)
Set the number of bins
Use bins when you want to request a particular number of intervals rather than a fixed interval width.
ggplot(mpg, aes(x = hwy)) +
geom_histogram(bins = 12, fill = "#2A9D8F")

Practical advice: try a few sensible values and compare the shape. Avoid selecting a binwidth simply because it produces a visually attractive result. The best choice preserves meaningful patterns without hiding important structure or exaggerating random fluctuations.
4. Set bin boundaries and closed intervals
Use boundary or center to control how bins align with the measurement scale. For example, if you want five-unit intervals with edges aligned at multiples of five, use binwidth = 5 and boundary = 0.
ggplot(mpg, aes(x = hwy)) +
geom_histogram(
binwidth = 5,
boundary = 0,
fill = "#2A9D8F",
colour = "white"
)
closed determines which side of each interval includes a value exactly on a boundary. It accepts "right" or "left". This matters when observations fall exactly on interval edges.
ggplot(mpg, aes(x = hwy)) +
geom_histogram(
binwidth = 5,
boundary = 0,
closed = "right"
)

5. Change histogram fill, outline and theme
Use fill to change the interior colour and colour to change the bar outline. When these are fixed styling choices, place them outside aes().
ggplot(mpg, aes(x = hwy)) +
geom_histogram(
binwidth = 3,
fill = "#3A86A8",
colour = "white",
linewidth = 0.4
) +
labs(
title = "Distribution of highway fuel economy",
subtitle = "Cars in the ggplot2 mpg dataset",
x = "Highway miles per gallon",
y = "Frequency"
) +
theme_minimal()
For a publication-ready chart, use a clear title, meaningful axis labels and a restrained colour palette. The fill colour should not distract from the distribution itself.
6. Compare distributions between groups
Map a categorical variable to fill to compare distributions. The mpg dataset includes drv, which identifies front-wheel, rear-wheel and four-wheel drive vehicles.
Overlapping histograms with transparency
Use position = "identity" and an alpha value below 1 to make overlapping bars visible.
ggplot(mpg, aes(x = hwy, fill = drv)) +
geom_histogram(
binwidth = 3,
position = "identity",
alpha = 0.45,
colour = "white"
) +
labs(
title = "Highway fuel economy by drive type",
x = "Highway miles per gallon",
y = "Frequency",
fill = "Drive type"
) +
theme_minimal()

Side-by-side histograms
Use position = "dodge" to place group bars next to one another within each bin.
ggplot(mpg, aes(x = hwy, fill = drv)) +
geom_histogram(
binwidth = 3,
position = "dodge",
colour = "white"
) +
labs(x = "Highway miles per gallon", y = "Frequency") +
theme_minimal()

7. Use density instead of frequency
A frequency histogram displays counts. A density-scaled histogram displays probability density, so the total area of the bars is approximately one. This makes it easier to compare the shape of distributions when sample sizes differ.
Map the y aesthetic to after_stat(density) inside geom_histogram().
ggplot(mpg, aes(x = hwy)) +
geom_histogram(
aes(y = after_stat(density)),
binwidth = 3,
fill = "#BFD7EA",
colour = "white"
) +
labs(
title = "Density-scaled histogram",
x = "Highway miles per gallon",
y = "Density"
)
Remember that density is not the same as the number of observations. The vertical axis changes meaning when you use after_stat(density).

8. Add a smooth density curve
Overlay geom_density() to show a smoothed estimate of the distribution. The histogram must also use density on the y-axis; otherwise, the curve and bars use different scales.
ggplot(mpg, aes(x = hwy)) +
geom_histogram(
aes(y = after_stat(density)),
binwidth = 3,
fill = "grey85",
colour = "white"
) +
geom_density(
colour = "firebrick",
linewidth = 1.1
) +
labs(
title = "Histogram with density curve",
x = "Highway miles per gallon",
y = "Density"
) +
theme_minimal()
The density curve is a smoothed estimate, not a line joining the tops of the bars. Its appearance depends on the bandwidth. A very small bandwidth can create a wavy curve; a very large bandwidth can hide meaningful peaks.
9. Create faceted histograms
When comparing several groups, separate panels can be easier to read than overlapping bars. Use facet_wrap() to create a panel for each category.
ggplot(mpg, aes(x = hwy)) +
geom_histogram(
binwidth = 3,
fill = "#2878B5",
colour = "white"
) +
facet_wrap(~ drv) +
labs(
title = "Highway fuel economy by drive type",
x = "Highway miles per gallon",
y = "Frequency"
) +
theme_minimal()

10. Zoom in without dropping observations
Use coord_cartesian() when you want to focus on a region of the x-axis while retaining the full dataset for the histogram calculation.
ggplot(mpg, aes(x = hwy)) +
geom_histogram(binwidth = 3) +
coord_cartesian(xlim = c(10, 40))
Be careful with scale limits such as scale_x_continuous(limits = c(10, 40)) or xlim(10, 40). These can remove observations outside the range before the statistical transformation calculates the bins. For visual zooming, coord_cartesian() is usually the safer choice.
11. Recognise skewness, clusters and outliers
Histograms are useful for spotting departures from symmetry. A right-skewed distribution has a longer tail toward larger values; a left-skewed distribution has a longer tail toward smaller values. Multiple peaks may indicate subgroups or a mixture of populations.

Do not identify an observation as an outlier from a histogram alone. Investigate the raw values, measurement process and relevant subject knowledge before deciding how to handle unusual observations.
12. Download histogram practice datasets
Use these small fictional datasets to practise bin selection, group comparisons and interpretation. They are demonstration data, not real survey or vehicle records.
- Download participant ages CSV — one numeric variable for basic histograms and binwidth experiments.
- Download vehicle fuel economy CSV — numeric highway mileage and drive-type groups for overlapping, dodged and faceted histograms.
- Download exam scores CSV — two fictional class groups for comparing score distributions.
Read a file into R with read.csv(), then pass the resulting data frame to ggplot().
ages <- read.csv("participant_ages.csv")
ggplot(ages, aes(x = age)) +
geom_histogram(
binwidth = 5,
boundary = 0,
fill = "#2878B5",
colour = "white"
) +
labs(x = "Age (years)", y = "Participants") +
theme_minimal()
To compare exam scores by class:
scores <- read.csv("exam_scores.csv")
ggplot(scores, aes(x = score, fill = group)) +
geom_histogram(
binwidth = 5,
position = "identity",
alpha = 0.45
) +
labs(x = "Exam score", y = "Students", fill = "Class") +
theme_minimal()
13. Interactive histogram explorer
Use the browser-based explorer below to change the number of bins and compare how bin width changes the visual impression of a distribution. This interactive example uses a small illustrative dataset and runs locally in your browser.
14. Common ggplot2 histogram mistakes
- Using a categorical variable on x: histograms are intended for continuous numeric variables. Use
geom_bar()for category counts. - Too many or too few bins: inspect several reasonable binwidth values and explain your choice.
- Mixing counts and density: a count histogram and a density curve do not share the same y scale. Use
after_stat(density)for the histogram layer. - Putting a fixed colour inside aes():
aes(fill = "steelblue")maps a literal string to a category. Usefill = "steelblue"outsideaes()for a fixed fill. - Overlooking missing values: inspect missing observations with
sum(is.na(data$variable))before interpreting the plot. - Using scale limits to zoom: scale limits can discard observations before binning. Use
coord_cartesian()to zoom the display. - Comparing unequal sample sizes using counts: consider density scaling when the goal is to compare distribution shapes rather than sample totals.
15. Practice exercises
- Create a histogram of
mpg$ctyusinggeom_histogram(). Label both axes clearly. - Plot
mpg$hwywith binwidth values of 2, 4 and 6. Explain how the apparent shape changes. - Use
boundary = 0andclosed = "right"to align and define the intervals. - Compare highway fuel economy across
drvcategories using overlapping histograms with transparency. - Create separate panels using
facet_wrap(~ drv). - Overlay a density curve on a density-scaled histogram and explain why the y-axis is not a frequency count.
- Load
exam_scores.csvand compare the two class score distributions. Comment on centre, spread and overlap.
When interpreting your results, describe the distribution's shape, centre, spread and any unusual features rather than simply stating which histogram looks higher.
Continue learning ggplot2
After learning histograms, explore other chart types and distribution visualisations in the complete ggplot2 tutorial. Histograms are especially useful alongside density plots, boxplots and violin plots when investigating numerical data.
ggplot2 FAQ
How do I create a histogram in ggplot2?
Map a continuous numeric variable to x and add geom_histogram(), for example ggplot(mpg, aes(x = hwy)) + geom_histogram().
What does binwidth mean in ggplot2?
binwidth sets the width of each histogram interval in the units of the variable. Smaller widths reveal more detail, while larger widths produce a more aggregated view.
What is the difference between bins and binwidth?
bins requests a number of intervals, whereas binwidth specifies the width of each interval. Use one to control the histogram's granularity.
How do I change histogram colours in ggplot2?
Set a fixed fill outside aes(), for example geom_histogram(fill = 'steelblue', colour = 'white'). Map fill inside aes() only when colour represents a variable.
How do I compare two distributions in ggplot2?
Map a grouping variable to fill and use position = 'identity' with alpha transparency, use position = 'dodge', or create separate panels with facet_wrap().
How do I add a density curve to a ggplot2 histogram?
Map the histogram y aesthetic to after_stat(density), then add geom_density() so both layers use a density scale.
What is the difference between a histogram and a bar chart?
A histogram groups continuous numeric values into intervals and displays their frequency or density. A bar chart compares distinct categories.
How do I zoom in on a histogram without removing observations?
Use coord_cartesian(xlim = c(lower, upper)) to zoom the display. Scale limits such as xlim() can remove observations before the histogram is calculated.