How to make Histogram with R

Histograms are frequently used in data analysis for visualizing data. Through a histogram, we can identify the distribution and frequency of the data. A histogram divides a continuous variable into groups (x-axis) and gives the frequency (y-axis) in each group. The function used to build a histogram is hist(). Below I will show a set of examples using the iris dataset, which comes with R.

Let’s start with a basic histogram:

hist(iris$Petal.Length)

Here is the basic histogram:
Plot-basic-histogram

Next, we add color and labels to the histogram:

hist(iris$Petal.Length, col="blue", xlab="Petal Length", main="Colored histogram")

Here is the histogram with color and labels:
Rplot-color-histogram

We can also add breaks to the histogram, which increases the number of bars and gives more information about the distribution:

hist(iris$Petal.Length, breaks=30, col="gray", xlab="Petal Length", main="Colored histogram")

Here is the histogram with more bars:
Rplot-breaks-histogram

In statistics, the histogram is used to evaluate the distribution of the data. In order to show the distribution, we will first display density (or probability) instead of frequency, by using the argument freq=FALSE. Secondly, we will use the function curve() to add a normal distribution line to the plot.

Here is the example:

# add a normal distribution line in histogram
hist(iris$Petal.Length, freq=FALSE, col="gray", xlab="Petal Length", main="Colored histogram")
curve(dnorm(x, mean=mean(iris$Petal.Length), sd=sd(iris$Petal.Length)), add=TRUE, col="red") #line

Here is the histogram with the normal distribution line, which makes it easy to see how far the data departs from a normal distribution:
Rplot-normal-distribution-histogram

That’s all about histograms in this post. If you have any questions, leave a comment below.

1 Comment

  1. VB
    Viktor B. May 14, 2019

    Dear Klodian,

    i have read your interesting article about histograms in R. In my work I need to create histograms starting strictly at the minimal value of the dataset and it must end strictly at the maximal value of dataset. i.e. the last bin has to end strictly at the max value of the dataset.
    Do you know how to create it in R? I have tried with hist() and ggplot histogram, with no luck.
    In your case start of iris$Petal.Length is at minimal value while the last bin ends at 7.0 althoug maximal value is 6.9 in iris dataset.
    In case of this dataset I have to create starting at minium(1.0) and ending at 6.9 having ten bins in total.

    Thanks in advance

    Reply

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.