RMarkdown : bookdown with plotly

标签 r knitr r-markdown plotly bookdown

我正在使用 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我想出了一个解决方案。注意,这只有效

  • 使用“knitr”按钮(参见 this post 解决方法)
  • 具有互联网连接 (1) 和 Plotly 帐户 (2)

  • (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/

    相关文章:

    r - 如何使用 dplyr 覆盖数据?

    r - XGBoost-具有变化的曝光/偏移的泊松分布

    r - 是否可以将 RMarkdown block 放入 Rmd 文件的表格单元格中?

    r - 打印在RStudio中使用R Markdown在函数中生成的图

    R Markdown - Highcharter - 在可见时动画图形,而不是在页面加载时?

    r - 在 R Markdown 模板中包含图像,无需为模板创建新目录

    R 连接到汤森路透 Eikon

    r - 当 hjust 和 vjust 是字符串时,为什么 geom_text() 会抛出强制错误?

    html - RMarkdown : Floating TOC and TOC at beginning

    r-markdown - 在同一个 Bookdown 项目中拥有 beamer_presentation 和 pdf_book