How To Make A Histogram On R

6 min read

How to make a histogram on R
Creating a histogram in R is a fundamental skill for anyone who wants to visualize the distribution of numeric data quickly and effectively. Whether you are exploring a new dataset, checking assumptions before running statistical tests, or simply communicating results to a non‑technical audience, a well‑crafted histogram reveals patterns such as skewness, modality, and outliers at a glance. In this guide you will learn the core concepts behind histograms, step‑by‑step instructions for building them with base R and the popular ggplot2 package, tips for customizing appearance, and answers to common questions that arise during the process The details matter here..


Understanding What a Histogram Shows

A histogram partitions the range of a continuous variable into consecutive, non‑overlapping intervals called bins (or classes). The height of each bar represents the count—or sometimes the density—of observations that fall into that bin. Unlike a bar chart for categorical data, the bins in a histogram are ordered and touch each other, emphasizing the underlying continuity of the variable.

Key points to remember:

  • Bin width influences the shape: too narrow produces a noisy plot; too wide hides important details.
  • Frequency vs. density: freq = TRUE (default) shows raw counts; freq = FALSE scales the area of all bars to 1, useful for comparing distributions with different sample sizes.
  • Outliers appear as isolated bars at the extremes; consider transforming the data or using a different binning strategy if they dominate the view.

With this conceptual foundation, let’s move to the practical side of making a histogram in R.


Step‑by‑Step Guide: Base R Histogram

1. Load or Create Your Data

# Example: built-in mtcars dataset
data(mtcars)
# Variable of interest: miles per gallon (mpg)
x <- mtcars$mpg

2. Basic Histogram with hist()

hist(x,
     main = "Histogram of MPG (mtcars)",
     xlab = "Miles per Gallon",
     ylab = "Frequency",
     col = "steelblue",
     border = "white")

Explanation of arguments

Argument Purpose
main Title of the plot
xlab Label for the x‑axis
ylab Label for the y‑axis
col Fill colour of the bars
border Colour of the bar edges
breaks (Optional) Number of bins or a vector of break points
freq TRUE for counts, FALSE for density

3. Adjusting Bin Width

You can let R choose the default number of bins (Sturges’ rule) or specify your own:

# 15 bins explicitly
hist(x, breaks = 15, col = "tomato", main = "MPG Histogram – 15 Bins")

# Custom break points (e.g., every 2 mpg)
hist(x, breaks = seq(10, 35, by = 2), col = "seagreen",
     main = "MPG Histogram – Custom Breaks")

4. Adding a Density Curve (Optional)

Overlaying a kernel density estimate helps assess normality:

hist(x, prob = TRUE, col = "lightgray", border = "white",
     main = "MPG Histogram with Density Curve",
     xlab = "Miles per Gallon")
lines(density(x), col = "darkred", lwd = 2)

Note: prob = TRUE is equivalent to freq = FALSE The details matter here..


Step‑by‑Step Guide: Histogram with ggplot2

The ggplot2 package implements the Grammar of Graphics, offering greater flexibility for layered aesthetics and faceting It's one of those things that adds up. No workaround needed..

1. Install and Load the Package

if (!requireNamespace("ggplot2", quietly = TRUE))
  install.packages("ggplot2")
library(ggplot2)

2. Basic Histogram

ggplot(mtcars, aes(x = mpg)) +
  geom_histogram(binwidth = 2,          # width of each bin
                 fill = "cornflowerblue",
                 colour = "white") +
  labs(title = "Histogram of MPG (ggplot2)",
       x = "Miles per Gallon",
       y = "Count") +
  theme_minimal()

Key ggplot2 components

  • aes(x = mpg) maps the variable to the x‑axis.
  • geom_histogram() creates the bars; binwidth controls bin size (alternatively use bins = 30).
  • fill and colour set interior and edge colours.
  • labs() adds titles and axis labels.
  • theme_minimal() applies a clean background; swap for theme_bw(), theme_classic(), etc.

3. Density Histogram

ggplot(mtcars, aes(x = mpg)) +
  geom_histogram(aes(y = ..density..),      # compute density instead of count
                 binwidth = 2,
                 fill = "lightgreen",
                 colour = "white") +
  geom_density(colour = "navy", size = 1.2) +
  labs(title = "Density Histogram of MPG",
       x = "Miles per Gallon",
       y = "Density") +
  theme_classic()

4. Faceting by a Categorical Variable

To compare MPG across cylinder counts:

ggplot(mtcars, aes(x = mpg)) +
  geom_histogram(binwidth = 2, fill = "orange", colour = "white") +
  facet_wrap(~ cyl, ncol = 3) +
  labs(title = "MPG Histograms by Number of Cylinders",
       x = "Miles per Gallon",
       y = "Count") +
  theme(strip.background = element_rect(fill = "lightgrey"))

Customizing Appearance for Publication‑Quality Graphics

Both base R and ggplot2 allow fine‑tuning. Below are common adjustments:

Goal Base R ggplot2
Change font size par(cex.png", width = 6, height = 4, dpi = 300)
Add vertical line (e.off()` ggsave("hist.Which means main = 1. ); dev.5, cex.2) theme(text = element_text(size = 14))
Save as high‑resolution PNG `png("hist.lab = 1.png", width = 1800, height = 1200, res = 300); hist(...g.

cept = mean(mpg)), col = "red", linetype = 2, size = 1)| | Change background color |par(bg = "lightyellow")|theme(panel.But background = element_rect(fill = "lightyellow"))| | Rotate x-axis labels |par(las = 2)|theme(axis. text.x = element_text(angle = 90, hjust = 1))| | Adjust bin transparency | Not directly supported |geom_histogram(..., alpha = 0.

Quick note before moving on That's the part that actually makes a difference..

Advanced Customization Examples

Adding a Mean Line and Standard Deviation Bands

# Calculate mean and standard deviation
mean_mpg <- mean(mtcars$mpg)
sd_mpg <- sd(mtcars$mpg)

ggplot(mtcars, aes(x = mpg)) +
  geom_histogram(binwidth = 2, fill = "steelblue", colour = "white", alpha = 0.On the flip side, 8) +
  geom_vline(xintercept = mean_mpg, col = "red", linetype = "dashed", size = 1. 2) +
  geom_vline(xintercept = c(mean_mpg - sd_mpg, mean_mpg + sd_mpg), 
             col = "darkgreen", linetype = "dotted", size = 1) +
  annotate("text", x = mean_mpg, y = 5, label = "Mean", col = "red", size = 4) +
  labs(title = "Histogram with Mean and ±1 SD",
       subtitle = "MPG distribution for 32 cars",
       x = "Miles per Gallon", y = "Count") +
  theme_minimal(base_size = 14) +
  theme(plot.

**Custom Color Palette and Grid Removal**

```r
ggplot(mtcars, aes(x = mpg, fill = cyl)) +
  geom_histogram(binwidth = 2, colour = "white", position = "identity", alpha = 0.6) +
  scale_fill_brewer(palette = "Dark2") +
  labs(title = "Overlaid Histograms by Cylinder Count",
       x = "Miles per Gallon", y = "Count", fill = "Cylinders") +
  theme_classic() +
  theme(legend.position = "bottom",
        panel.grid.major = element_line(colour = "grey90"),
        panel.grid.minor = element_blank())

Choosing the Right Approach

For quick exploratory analysis, base R histograms are faster and require less code. On the flip side, ggplot2 excels when:

  • You need publication‑ready graphics with precise control over aesthetics.
  • Your analysis involves multiple variables requiring faceting or layered geoms.
  • You want to combine histograms with density curves, boxplots, or other visual elements.

Both methods integrate smoothly into R Markdown documents, allowing reproducible research workflows. The choice ultimately depends on your audience and the complexity of your visualization needs.


Conclusion

Creating effective histograms in R is straightforward with either base R or ggplot2. By mastering bin width selection, density scaling, faceting, and aesthetic customization, you can transform raw data into clear, compelling visual stories. Think about it: base R offers a rapid, built‑in solution for basic distributions, while ggplot2 provides a powerful, extensible framework for sophisticated, layered graphics. Whether you're conducting exploratory data analysis or preparing figures for publication, these techniques will enhance your ability to communicate quantitative insights effectively.

Newly Live

Latest from Us

Kept Reading These

A Few More for You

Thank you for reading about How To Make A Histogram On R. We hope the information has been useful. Feel free to contact us if you have any questions. See you next time — don't forget to bookmark!
⌂ Back to Home