我正在使用 bookdown
使用 RMarkdown 打包以生成类似于 this 的基于 Web 的书籍,同样可以选择下载该书的 pdf 版本。
我已包含 plotly
我的“书”中的图表在本书的 html 版本中运行良好。作为交互式,在 YAML header 中包含 pdf 输出时,“构建书”按钮会引发错误。
基于 this description我找到了一种使用常规 RMarkdown 文件的解决方法,可以使用 plotly
创建 pdf。图形输出。一个最小的解决方案(外部 bookdown)如下所示:
---
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)
有没有办法将这个解决方案包含在 bookdown 中,以便图表在 html 输出中自动交互,在 pdf 输出中静态(png)?
最佳答案
基于 this blogpost我想出了一个解决方案。注意,这只有效
(1) 见 this link在本地导出静态图像(由于安装失败,我没有开始工作
PhantomJS
)(2) Plotly 的用户配额目前为每个用户每天 100 个地块/网格
---
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"))
```
关于RMarkdown : bookdown with plotly,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46780101/