6

I'm using the bookdown package with RMarkdown to generate web-based book similar to this, likewise with the option to download a pdf-version of the book.

I've included plotly graphs in my "book" which work nicely in the html-version of the book. Being interactive, the button "build book" throws an error when including pdf output in the YAML-header.

Based on this description I've found a workaround with a regular RMarkdown File to create pdfs with plotly graphs outputs. A minimal solution (outside bookdown) looks like this:

---
title: "test"
output:
  pdf_document: default
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(plotly)

Sys.setenv("plotly_username" = "username")
Sys.setenv("plotly_api_key" = "API")
```


```{r cars}
library(plotly)
p <- plot_ly(x = c(1,2,3,4), y = c(2,4,1,3), type = 'scatter', mode = 'lines')
plotly_IMAGE(p, format = "png", out_file = "output.png")

```
![Caption for the picture.](output.png)

Is there a way to include this solution within bookdown, so that the graphs are automagically interactive in the html output and static (png) in the pdf output?

1 Answer 1

1

Based on this blogpost I was able to come up with a solution. Note, this only works

  • with the "knitr" button (see this post for a workaround)
  • with an internet connection (1) and Plotly Account (2)

(1) See this link to export static images locally (which I didn't get to work since I failed installing PhantomJS)

(2) Plotly has a user Quota of currently 100 plots / grids per user per day

---
title: "test"
output:
  html_document: default
  pdf_document: default
  word_document: default
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(plotly)
library(pander)
Sys.setenv("plotly_username" = "YOUR PLOTLY USERNAME")
Sys.setenv("plotly_api_key" = "API KEY")

output <- knitr::opts_knit$get("rmarkdown.pandoc.to") # html / latex / docx

```


```{r, results="asis"}

print(output)

p <- plot_ly(x = c(1,2,3,4), y = c(2,4,1,3), type = 'scatter', mode = 'lines')

filename <- "output.png"

if(output %in% c("latex","docx")){
  plotly_IMAGE(p, format = "png", out_file = filename)
  pandoc.image(filename)
} else if(output == "html"){
  p
} else(print("No format defined for this output filetype"))


```
Sign up to request clarification or add additional context in comments.

2 Comments

With html as the output format don't you want to output the full plotly object so that the user can interact with it?
The issue I had was with generating the pdf Version of the book

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.