Learn R Programming  /  Base Graphics  /  Histogram

Histogram

A histogram bins numeric data into intervals and shows how many observations fall into each one — the standard way to see a variable's overall shape, spread, and skew.

A Basic Histogram

R Code
set.seed(1)
x <- rnorm(500, mean = 50, sd = 10)

hist(x, main = "Distribution of X", col = "lightgreen", xlab = "Value")

Controlling the Number of Bins

R Code
hist(x, breaks = 10, col = "skyblue", main = "Fewer, Wider Bins")
hist(x, breaks = 50, col = "skyblue", main = "More, Narrower Bins")
💡 Tip
breaks is a suggestion, not a strict command - R may adjust the exact number slightly to produce clean bin boundaries. For full control, pass a vector of exact cut points instead of a single number.

Overlaying a Density Curve

R Code
hist(x, freq = FALSE, col = "lightgreen", main = "Histogram with Density Curve")
lines(density(x), col = "darkred", lwd = 2)

Advanced: Comparing Two Distributions

🚀 Advanced Example
Overlapping two semi-transparent histograms on the same axes is a quick way to visually compare two groups.
R Code
group_a <- rnorm(300, mean = 50, sd = 8)
group_b <- rnorm(300, mean = 60, sd = 8)

hist(group_a, col = rgb(0,0,1,0.4), xlim = c(20,90), main = "Group A vs Group B")
hist(group_b, col = rgb(1,0,0,0.4), add = TRUE)
legend("topright", legend = c("Group A","Group B"), fill = c("blue","red"))

Key Points

  • hist() bins numeric data and shows how many values fall into each bin.
  • breaks controls roughly how many bins are drawn.
  • freq = FALSE switches the y-axis to density, needed before overlaying lines(density(x)).
  • add = TRUE layers a second histogram on top of the first for visual comparison.