# How to create a histogram (in R)

## Task

A histogram is a very common and useful data visualization. It displays an approximation of the distribution in single series of data points (one variable) by grouping the data into bins, each bin draw as a vertical bar. How can we create such a visualization?

Related tasks:

- How to create basic plots
- How to create a box (and whisker) plot
- How to add details to a plot
- How to create bivariate plots to compare groups
- How to plot interaction effects of treatments

## Solution

We will create some random data, but that’s just for demonstration purposes. You can apply the answer below to any data. Simply replace the data variable with your real data (a list, a column of a dataframe, etc.).

1

data <- rnorm(1000)

We can use R’s hist() function to create the histogram.

1

hist(data)

The y axis in a histogram is frequency, or the number of occurences. You can change it to probabilities instead.

1

hist(data, prob = TRUE)

You can also choose your own bin boundaries. You might specify the number of bin breaks you want, or you can choose the exact bin breaks that you want.

1
2

hist(data, breaks = 8) # Specify number of bin breaks
hist(data, breaks = c(seq(-5, 5, 1))) # Choose exact bin breaks

Content last modified on 24 July 2023.

See a problem? Tell us or edit the source.

Contributed by Elizabeth Czarniak (CZARNIA_ELIZ@bentley.edu)