How to create Histograms in R

R Histograms

A Histogram is the graphical representation of the distribution of numeric data. It takes only one numeric variable as input. The variable is cut into several bars (also called bins), and the number of observation per bin is represented by the height of the bar. Note that, the shape of the histogram can be different following the number of bins we set.

To plot a histogram, we use one of the axes as the frequency or count of values and another axis as the range of values divided into buckets.

R provides a hist() function which is used to create histograms. This function takes a vector as an input with some parameters to plot histograms.

Syntax:

Here,

v is a vector containing numeric values

main is the title of the chart

col is for color of the bar or bins

border is for border color

xlab is the description of the x-axis

xlim is the range of values on the x-axis

ylim is the range of values on the y-axis

breaks are used to specify the width of each bar

Example:

Let’s create a simple histogram using input vector, label, col and border parameters.

Output:

R Histograms Example1

Range of x and y values

xlim and the ylim parameter are used to set the range of values in x-axis and y-axis respectively.

Example:

Let’s see an example:

Output:

R Histograms Example 2

Histograms with different breaks

We can specify the width of the bar through the breaks parameter.

Example 1:

Let’s see an example to create a histogram with 5 breaks.

Output:

R Histograms Example 3

Example 2:

Let’s see another example to create a histogram with 20 breaks:

Output:

R Histograms Example 4

Bins with different Color

Example:

Output:

R Histograms Example 5