# How to display the curve on the histogram using ggplot2 in R?

R ProgrammingServer Side ProgrammingProgramming

Mostly, we use histogram to understand the distribution of a variable but if we have an overlay line on the histogram that will make the chart smoother, thus understanding the variation will become easy. To display the curve on the histogram using ggplot2, we can make use of geom_density function in which the counts will be multiplied with the binwidth of the histogram so that the density line will be appropriately created.

## Example

Consider the below data frame:

Live Demo

> x<-rpois(200,5)
> df<-data.frame(x)
> head(df,20)

## Output

   x
1  4
2  5
3  6
4  4
5  9
6  2
7  1
8  5
9  5
10 7
11 6
12 9
13 5
14 2
15 12
16 4
17 8
18 8
19 4
20 3

## Example

> library(ggplot2)
> ggplot(df,aes(x))+geom_histogram(binwidth=1.1)

## Output:

Creating the histogram with curve on the graph:

## Example

> ggplot(df,aes(x))+geom_histogram(binwidth=1.1)+geom_density(aes(y=1.1*..count..))

## Output:

Published on 19-Nov-2020 05:20:37