问题描述
以下 Rmarkdown 以 HTML 格式呈现 3D 图形,但不以 PDF 格式呈现.
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
```
图表的快照如下所示:
根据plotly 帮助页面:
如果您将 rmarkdown 与 HTML 输出一起使用,则在代码块中打印一个 plotly 对象将生成一个交互式 HTML 图形.当使用带有非 HTML 输出的 rmarkdown 时,打印一个 plotly 对象将导致图形的 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,WP2