2016-10-26 58 views
9

以下Rmarkdown以HTML形式绘制三维图形,但不以PDF形式绘制。Plotly as png in knitr/rmarkdown

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 
``` 

曲线图的快照显示如下:

enter image description here

按照plotly help page

如果使用rmarkdown与HTML输出,打印plotly对象在代码块将导致交互式HTML图形。 当使用非HTML输出的rmarkdown时,打印一个阴谋对象会导致图形的PNG截图。

有没有办法在PDF中渲染绘图图形?

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

​​

回答

4

我已经创建了一个小的解决办法,它保存在本地plotly图像为PNG文件和进口它回到RMD文件。 您需要的包webshot,可将其加载通过:

​​

更进一步,你需要通过

webshot::install_phantomjs() 

然后安装phantomjs(当phantomjs在PATH),你可以创建你RMD文件:

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

这对我有用..也许这也是你的解决方法!

+1

我目前正在做同样的事情,但得到的图像中间有一个很大的文本错误:“WebGL不支持您的浏览器 - ...”。任何想法如何解决这个问题? – Megatron

+1

我应该澄清 - 我试图从3D散点图中生成PNG时出现WebGL错误(未在我的问题中显示) – Megatron

+0

还有我的小例子,这不正常吗? –

2

由于@hrbrmstr评论,export()以前根本不支持WebGL,但更新的版本支持通过RSelenium导出到PNG(请参阅help(export, package = "plotly"))。如果您需要pdf导出,您必须为云帐户付款 - https://plot.ly/products/cloud/

+0

似乎目前在GitHub(目前为4.5.6.9000)中的开发版尚未准备好,因为运行export()只会产生一个空白图像。 – Megatron

0

R markdown compile error:相同的问题。你需要选择你想要的格式,试着看看我的。

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

KNIT

0

我做什么,这样渲染PDF的工作,但你仍然可以在其他针织类型和作为R工作室rmarkdown文件的互动情节是:

这正好在安装块(或真的,此文件中上旬):

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

那么这种使用基于你是什么样的文件CRE渲染任何plotly情节ating:

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

在该示例中base_plot是该图的名称。