## Generating a density plot

The density plot uses the kernel density estimation to generate the distribution. In this recipe, we will utilize the `density()`

function to generate a plot. The density plots can be used to study the underlying distribution of the data.

### Getting ready

We will use the `quantmod`

package to download the stock prices for Microsoft and also calculate monthly returns:

install.packages("quantmod") library(quantmod)

### How to do it…

We will download the data in R using the `getSymbols()`

function. Once we have the data, we can calculate the monthly returns using the `monthlyReturns()`

function:

prices = c("MSFT") getSymbols(prices) msft_m = monthlyReturn(MSFT)

In order to generate a density plot, we will first estimate the kernel density using the `density()`

function in R. Please note that we have plotted a density plot over the histogram and, hence, we need to use the `lines()`

function. The `lines()`

function will allow us to plot a density plot over the histogram:

msft_d = density(msft_m...