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)
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:

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:

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:

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

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