在knitr/rmarkdown中以png格式绘制 [英] Plotly as png in knitr/rmarkdown

查看:93
本文介绍了在knitr/rmarkdown中以png格式绘制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下Rmarkdown使用HTML而不是PDF绘制可绘制的3D图形.

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.Length, y=~Sepal.Width, z=~Petal.Length, 
             color=~Species, symbols=c(0,1), type="scatter3d", mode="markers")
p
```

图形的快照如下所示:

根据全面帮助页面:

如果将rmarkdown与HTML输出一起使用,则在代码块中打印可打印对象将产生交互式HTML图形. 将rmarkdown与非HTML输出一起使用时,打印图形对象将产生图形的png屏幕截图.

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.

有没有一种方法可以在PDF中绘制可打印图形?

Is there a way to render the plotly graph in a PDF?

注意: rmarkdown::render()中的错误是:

Error: Functions that produce HTML output found in document targeting latex output.
Please change the output type of this document to HTML. Alternatively, you can allow
HTML output in non-HTML formats by adding this option to the YAML front-matter of
your rmarkdown file:

  always_allow_html: yes

Note however that the HTML output will not be visible in non-HTML formats.

推荐答案

我创建了一个小解决方法,该方法将本地图像保存为png文件,然后将其重新导入RMD文件. 您需要包webshot,可以通过以下方式加载:

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")

此外,您需要通过以下方式安装phantomjs

Further more, you need to install phantomjs via

webshot::install_phantomjs()

然后(当phantomjs位于PATH中时),您可以创建RMD文件:

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!

这篇关于在knitr/rmarkdown中以png格式绘制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆