Show Sidebar Hide Sidebar

Embedding Graphs with Knitr in R

How to embed Plotly graphs in Rmd files.

New to Plotly?

Plotly's R library is free and open source!
Get started by downloading the client and reading the primer.
You can set up Plotly to work in online or offline mode.
We also have a quick-reference cheatsheet (new!) to help you get started!

Version Check

Version 4 of Plotly's R package is now available!
Check out this post for more information on breaking changes and new features available in this version.

library(plotly)
packageVersion('plotly')
## [1] '4.5.6.9000'

Embedding plotly graphs in Rmd files

If you are using rmarkdown with HTML output, printing a plotly object in a code chunk will result in an interactive HTML graph. When using rmarkdown with non-HTML output, printing a plotly object will result in a png screenshot of the graph.

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

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

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

Another way to print multiple objects is by using a lapply:

library(plotly)

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

Alternatively, you can use for loops:

library(plotly)

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

You can also host your figures on a plotly server via plotly_POST() which returns a figure object. When a figure object is printed in an rmarkdown/knitr document, it embeds the figure as an iframe, displaying the plot as it appears on your plotly account.

f <- plotly_POST(p)
class(f)
f

You can control the height/width of that iframe through the height/width knitr chunk options, but the figure object also contains the relevant url so you complete control over embedding your figure. The post has more details on how to embed plotly graphs with HTML iframes, but could also use plotly's built-in image export by simply adding a .png (or similar) extension.

htmltools::tags$img(src = paste0(f[["url"]], ".png"))

<!--htmlpreserve--><!--/htmlpreserve-->

Still need help?
Contact Us

For guaranteed 24 hour response turnarounds, upgrade to a Developer Support Plan.