簡體   English   中英

在 R Markdown PDF output 中更改 output plotly 圖表大小的寬度

[英]Change output width of plotly chart size in R Markdown PDF output

在 R markdown 文件中,有人知道為什么在生成 pdf 文件時out.widthout.heightfigure.widthfigure.height參數不會更改 plotly 圖表大小嗎? (我精確地說,這些參數使用plot函數可以完美工作)

請在下面找到帶有 Rmarkdown 文件的可重現示例

在這個例子中,我希望 plotly 圖表像 plot 圖表一樣占據整個工作表。

---
title: "Change chart size chart on pdf file using plotly"
output:
  pdf_document: default
---

```{r setup, include = FALSE}
knitr::opts_chunk$set(echo=FALSE,message=FALSE)

```

## Parameters doesn't work with plotly  

```{r, out.width='100%',out.height='100%',fig.height=20, fig.width=15, fig.align="left"}
library(plotly)
plot_ly(x = cars[1:10,]$speed,y = cars[1:10,]$dist)
```

## Parameters works using plot function

```{r,out.width='130%',out.height='100%', fig.height=20, fig.width=15, fig.align="left"}
plot(cars[1:10,])
```

在此處輸入圖像描述

繪圖圖形主要是為交互式輸出設計的,因此,在導出為 PDF 中的靜態圖像時,可能會表現得有點奇怪。 這個問題過去有一些類似的帖子,似乎來自 webshot 如何創建靜態圖像。

您可以通過在創建圖形時強制繪制圖形尺寸來解決此問題。 plot_ly函數具有參數widthheight ,可讓您設置結果圖的輸出尺寸。

如果您想在 PDF 報告中包含 HTML 對象,您可以使用webshot包,該包本質上截取渲染圖的屏幕截圖並將其轉換為靜態圖像以供您包含在報告中。 這在bookdown book 中有很好的解釋。 要安裝它,您需要運行:

install.packages('webshot')
webshot::install_phantomjs()

一旦安裝了webshot ,它應該會自動運行:

---
title: "Change chart size chart on pdf file using plotly"
output:
  pdf_document: default
papersize: a4
---

```{r include=FALSE}
knitr::opts_chunk$set(echo = FALSE, warning = FALSE, message = FALSE)
library(plotly)
```

```{r, out.width="100%"}
plot_ly(x = cars[1:10,]$speed,y = cars[1:10,]$dist, width = 1000, height = 1200)
```

在此處輸入圖片說明

如果我能弄清楚它為什么起作用,我會更新這個答案,但希望有幫助!

使用 r markdown pdf 處理繪圖時需要非常小心。

在創建情節圖時,

  • 不要忘記明確設置圖形的大小(寬度和高度)
  • 使用 out.width 和 out.height 的塊選項。 他們都接受 pt,mm,in,px,%
  • 如果您在 pdf 中生成乳膠輸出,則 'px' 將不起作用。

請找到下面的圖形代碼和相同的輸出。

f <- list(
    size = 30,
    family = 'sans-serif'
  )
  m <- list(
    l = 100,
    r = 50,
    b = 0,
    t = 0,
    pad = 4
  )

p <- plot_ly(width = 800, height = 800) %>% 
  add_markers(data = pressure, x = pressure$temperature, y = pressure$pressure) %>% 
  layout(font = f, margin = m)
p

由此產生的輸出具有大小和邊距

現在修改代碼塊選項后如下:

```{r pressure2, echo=FALSE, out.height="150%", out.width="150%"}
f <- list(
    size = 30,
    family = 'sans-serif'
  )
  m <- list(
    l = 100,
    r = 50,
    b = 0,
    t = 0,
    pad = 4
  )

p <- plot_ly(width = 800, height = 800) %>% 
  add_markers(data = pressure, x = pressure$temperature, y = pressure$pressure) %>% 
  layout(font = f, margin = m)
p
```

你會得到一個更大的圖表

繼續編碼!

您是否嘗試過僅使用fig.heightfig.width選項並刪除out.widthout.height

{r, fig.height=6, fig.width=9.5}

我正在玩 plotly,我已經成功地使用了 HTML 筆記本。 這是一個多一點的試驗和錯誤,但你不必重建地塊。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM