# How To Make Density Plots with ggplot2 in R?

• Last Updated : 05 Oct, 2021

In this article, we are going to see how to make Density plots with ggtplot2 in R Programming language.

To create a density plot in R using ggplot2, we use the geom_density() function of the ggplot2 package.

Syntax: ggplot( aes(x)) + geom_density( fill, color, alpha)

Parameters:

• fill: background color below the plot
• color: the color of the plotline
• alpha: transparency of graph

## Creating basic Density Plot with ggplot2

Here we are going to create a density plot.

## R

 `# create dataframe``set.seed``(1234)``df <- ``data.frame``(value =``round``(``c``(``rnorm``(200,``                                      ``mean=100,``                                      ``sd=7))))`` ` `# import libraries ggplot2``library``(ggplot2)  `` ` `# create density plot`` ``ggplot``(df, ``aes``(x=value)) + ``geom_density``()`

Output:

### Color Customization

To change color, we use the color property of the geom_density() function.

## R

 `# create dataframe``set.seed``(1234)``df <- ``data.frame``(value =``round``(``c``(``rnorm``(900,``                                      ``mean=60, ``                                      ``sd=21))))`` ` `# import libraries ggplot2``library``(ggplot2)     `` ` `# create density plot with desired colours`` ``ggplot``(df, ``aes``(x=value)) + ``geom_density``(color=``"green"``)`

Output:

To change background color, we use the fill property of geom_density() function.

## R

 `# create dataframe``set.seed``(1234)``df <- ``data.frame``(value =``round``(``c``(``rnorm``(900,``                                      ``mean=60, ``                                      ``sd=21))))`` ` `# import libraries ggplot2 ``library``(ggplot2)       `` ` `# create density plot with desired colours`` ``ggplot``(df, ``aes``(x=value)) + ``geom_density``(fill=``"#77bd89"``,``                                         ``color=``"#1f6e34"``,``                                         ``alpha=0.8)`

Output:

### Log scale customization:

When x or y-axis data is very large, we can draw plots with log scale using the following.

Syntax: plot+ scale_x_log10()

## R

 `# create dataframe``set.seed``(1234)``df <- ``data.frame``(value =``round``(``c``(``rnorm``(9000,``                                      ``mean=600000, ``                                      ``sd=210000))))`` ` `# import libraries ggplot2``library``(ggplot2)      `` ` `# create density plot with log scale`` ``ggplot``(df, ``aes``(x=value)) + ``geom_density``() + ``scale_x_log10``()`

Output:

My Personal Notes arrow_drop_up