Similar to the histogram, the density plots are used to show the distribution of data. Additionally, density plots are especially useful for comparison of distributions. For example, I often compare the levels of different risk factors (i.e. cholesterol levels, glucose, body mass index) among individuals with and without cardiovascular disease. Also, with density plots, we can illustrate how the distribution of a particular variable change over time.

The function we use for making the density plot is sm.density.compare() from sm package. To install and load the package use the code below:

install.packages("sm") library(sm)

In this example, I am using iris data set and comparing the distribution of the length of sepal for different species. After you load the dataset run the code below to build the density plot.

sm.density.compare(iris$Sepal.Length, iris$Species, xlab="Species") title(main="Distributions of Species")

Here is the plot.



To make a fancy density plot, Chris shared a R script with us: