Plotly as png in knitr/rmarkdown

后端 未结 4 1256
一生所求
一生所求 2020-12-13 11:12

The following Rmarkdown renders the plotly 3D graph in HTML, but not in PDF.

Testing plotly

```{r}
library(plotly)
p <- plot_ly(data=iris, x=~Sepal.Lengt         


        
相关标签:
4条回答
  • 2020-12-13 11:18

    As @hrbrmstr commented, export() previously didn't support WebGL at all, but more recent versions support exporting to png via RSelenium (see help(export, package = "plotly")). If you need pdf export, you'll have to pay for a cloud account -- https://plot.ly/products/cloud/

    0 讨论(0)
  • 2020-12-13 11:30

    What I do so that rendering to PDF's work but you can still have the interactive plots in other knit types and in rmarkdown files in r studio is:

    this goes in the setup block (or really, anywhere early in the file):

    is_pdf <- try (("pdf_document" %in% rmarkdown::all_output_formats(knitr::current_input())), silent=TRUE)
    is_pdf <- (is_pdf == TRUE)
    

    then this is used to render any plotly plot based on what kind of document you are creating:

    if (is_pdf) { export(base_plot) } else {base_plot}
    

    in the example base_plot is the name of the plot.

    0 讨论(0)
  • 2020-12-13 11:39

    I have created a little workaround, which saves the plotly images locally as png-file and imports it back to the RMD file. You need the package webshot, which you can load via:

    install.packages("webshot")
    

    Further more, you need to install phantomjs via

    webshot::install_phantomjs()
    

    Then (when phantomjs is in your PATH), you can create your RMD file:

    ---
    title: "Untitled"
    output: pdf_document
    ---
    
    ```{r}
    library(plotly)
    p <- plot_ly(economics, x = ~date, y = ~unemploy / pop)
    
    tmpFile <- tempfile(fileext = ".png")
    export(p, file = tmpFile)
    ```
    ![Caption for the picture.](`r tmpFile`)
    

    This works for me .. perhaps it's a workaround for you, too!

    0 讨论(0)
  • 2020-12-13 11:39

    Same issue with R markdown compile error:. You need to choose what format you want to KNIT to, tried to look at mine.

    ---
    title: "<img src='www/binary-logo.jpg' width='240'>"
    subtitle: "[<span style='color:blue'>binary.com</span>](https://github.com/englianhu/binary.com-interview-question) Interview Question I"
    author: "[<span style='color:blue'>®γσ, Lian Hu</span>](https://englianhu.github.io/) <img src='www/ENG.jpg' width='24'> <img src='www/RYO.jpg' width='24'>白戸則道®"
    date: "`r Sys.Date()`"
    output:
      tufte::tufte_html:
        toc: yes
      tufte::tufte_handout:
        citation_package: natbib
        latex_engine: xelatex
      tufte::tufte_book:
        citation_package: natbib
        latex_engine: xelatex
    link-citations: yes
    ---
    

    0 讨论(0)
提交回复
热议问题