R-Markdown is a great way to create dynamic documents with embedded chunks of
R code. The document is self contained and fully reproducible which makes it very easy to share. This post will be the first in a multi part series on how to embed Plotly graphs in R-Markdown documents as well as presentations.
R-Markdown is a flavor of markdown which allows R-users to embed R code into a markdown document. The document is then ‘knit’ using knitr to create a HTML file.
We’ll use R-Studio to create our R-Markdown document. You can download it here -> http://www.rstudio.com/products/rstudio/download/
Next we’ll install a few packages just to ensure we have everything we need to get started.
# Not run
- Note: you can download the function definition for
- Now we should be good to go…
Creating a R-Markdown document
File -> New File -> R Markdownas shown below.
You should now see a dialog as shown below. Select ‘Document’ in the left panel and fill in title and author field and hit ‘OK’.
- You should now have a document which looks like this –
To embed R code into the document, code needs to be inserted as shown below.
Inserting a Plotly graph
Inserting an awesome interactive Plotly chart is as simple as printing out the plotly object in a code chunk. Use the code snippet below.
source("Yahoo Stock Data Pull.R")
AAPL <- GetYahooData("AAPL")
IBM <- GetYahooData("IBM")
# Plotly chart
mat <- data.frame(Date = AAPL$Date,
AAPL = round(AAPL$Adj.Close,2),
IBM = round(IBM$Adj.Close,2))
p <- mat %>%
plot_ly(x = Date, y = AAPL, fill = "tozeroy", name = "Microsoft") %>%
add_trace(y = IBM, fill = "tonexty", name = "IBM") %>%
layout(title = "Stock Prices",
xaxis = list(title = "Time"),
yaxis = list(title = "Stock Prices"))
p # Thats it !
Knitting the R-Markdown document
Now that our R-Markdown document is complete with text, code and graphs, we can go ahead and click the little ‘Knit HTML’ button to generate a HTML file.
We now have a nicely formatted HTML file !
More to come…