2016-10-26 55 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是該圖的名稱。