Embedding Graphs in RMarkdown Files in R

How to embed R graphs in RMarkdown files.


New to Plotly?

Plotly is a free and open-source graphing library for R. We recommend you read our Getting Started guide for the latest installation or upgrade instructions, then move on to our Plotly Fundamentals tutorials or dive straight in to some Basic Charts tutorials.

Embedding R Graphs in RMarkdown files

If you are creating R charts in an RMarkdown environment with HTML output (such as RStudio), simply printing a graph you created using the plotly R package in a code chunk will result in an interactive HTML graph in the viewer.

When using RMarkdown with non-HTML output, printing a graph you created using the plotly R package will result in a .png screenshot of the graph being generated.

library(plotly)
p <- plot_ly(economics, x = ~date, y = ~unemploy / pop)
p

<!--htmlpreserve-->

<!--/html_preserve-->

Sometimes, you may want to print a list of graphs in an RMarkdown document.

If, for some reason, you don't want to use the subplot() function, you can render a list of htmlwidgets in a single code chunk using the tagList() function from the htmltools package:

htmltools::tagList(list(p, p))

<!--htmlpreserve-->

<!--/html
preserve-->

Another way to print multiple graphs in an RMarkdown document with the plotly R package is by using the lapply function:

library(plotly)

htmltools::tagList(lapply(1:3, function(x) { plot_ly(x = rnorm(10)) }))

<!--htmlpreserve-->

<!--/html_preserve-->

Alternatively, you can use a for loop instead of lapply:

library(plotly)

l <- htmltools::tagList()
for (i in 1:3) {
  l[[i]] <- plot_ly(x = rnorm(10))
}
l

<!--htmlpreserve-->

<!--/html_preserve-->

Embedding Chart Studio Graphs in RMarkdown Files

When you publish your plots to Chart Studio via the api_create() function, a figure object is returned to your R session.

When a Chart Studio figure object is rendered in an RMarkdown document, it is embedded as an iframe, displaying the plot as it appears on your Chart Studio account.

f <- api_create(p)
class(f)
f

You can control the height and width of that iframe through the height/width knitr chunk options, but the figure object also contains the relevant URL so you have complete control over embedding your figure.

This post has more details on how to embed Chart Studio graphs within HTML iframes, but you could also use Chart Studio's built-in image export by simply adding a .png or .jpeg file extension to the end of the figure's URL.

For example, view the static image of https://plotly.com/~chris/1638 at https://plotly.com/~chris/1638.png.