Density Plots

Learn how to create density plots using ggplot and density functions.

Features

We use density plots to visualize the distribution of a continuous variable. The plot displays the density or probability of occurrence of data points along the x-axis, with the y-axis representing the probability density. This plot provides a smooth estimate of the data distribution, which helps us identify patterns and trends in the data. It is a valuable tool for exploring data and comparing the distributions of different variables or datasets.

Press + to interact
Density chart
Density chart

Density plot with plot()

We use two different built-in functions to create a density plot in R. We first process the data in the density() function, and we supply it to the plot() function. The syntax structure is as follows:

# Syntax structure
plot(density(<data>))

Now, we will create a basic density plot using the mtcars dataset.

Press + to interact
# We use `airquality` dataset in this exercise
head(mtcars) # Preview of the dataset
plot(density(mtcars$mpg)) # Process the data and then plot the chart
  • Line 3: We first process the mpg column of the mtcars dataset and then supply it to the
...