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.

Generating a density plot

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) ...

Get R: Recipes for Analysis, Visualization and Machine Learning now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.