如何使用动态创建的选项卡和 for 循环显示 ggplotly 绘图?

use*_*715 3 for-loop r-markdown plotly

我有 R markdown 文档,我想动态创建其中包含 ggplotly 图形的选项卡

---
output: html_document
---

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

```{r}
library(ggplot2)
library(plotly)
```

```{r}
fig=ggplot(cars)+geom_point(aes(speed, dist))
```

# level 1
## level 2{.tabset .tabset-pills}

```{r echo=FALSE, results='asis'}

for (h in 1:3){
  cat("###", h,'{-}',  '\n\n')
 ggplotly(fig)
  cat( '\n\n')
}
```
Run Code Online (Sandbox Code Playgroud)

我知道它与普通ggplot图表不同,我在这里查看了解决方案:在此处输入链接描述,但它对我不起作用

ste*_*fan 5

按照这篇文章,可以这样实现:

编辑:在这篇文章之后,我添加了两个函数来将fig.width和传递fig.height给 ggplotly。

编辑2:添加了额外使用s的代码plotly::subplot

---
title: test
date: "20 5 2020"
output: html_document
---

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

```{r}
library(ggplot2)
library(plotly)
```

```{r, echo=FALSE}
# Get the current figure size in pixels:
get_w <- function() {
  with(knitr::opts_current$get(c("fig.width", "dpi", "fig.retina")),
       fig.width*dpi/fig.retina)
}

get_h <- function() {
  with(knitr::opts_current$get(c("fig.height", "dpi", "fig.retina")),
       fig.height*dpi/fig.retina)
}
```

```{r}
fig <- ggplot(cars) + 
  geom_point(aes(speed, dist))
```

# level 1

## level 2 {.tabset .tabset-pills}

```{r, include=FALSE}
htmltools::tagList(ggplotly(fig))
```

```{r echo=FALSE, results='asis', fig.width=4, fig.height=4}
fig <- ggplotly(fig, width = get_w(), height = get_h())
for (h in 1:3) {
  cat("###", h, '{-}',  '\n\n')
  print(htmltools::tagList(plotly::subplot(fig, fig, nrows=2, heights = c(0.1, 0.9))))
  cat( '\n\n')
}
```
Run Code Online (Sandbox Code Playgroud)