如何显示具有动态创建的选项卡和for循环的ggplotly图?

问题描述 投票:2回答:2

我有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')
}
```

[我了解它与正常的ggplot图不同,我在这里查看了解决方案:enter link description here,但对我不起作用

for-loop r-markdown plotly
2个回答
1
投票

遵循此post,可以像这样实现:

编辑:在此post之后,我添加了两个函数来将fig.widthfig.height传递给ggplotly。

---
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=6, fig.height=6}
for (h in 1:3) {
  cat("###", h, '{-}',  '\n\n')
  print(htmltools::tagList(ggplotly(fig, width = get_w(), height = get_h())))
  cat( '\n\n')
}
```

-1
投票

也从this link找到了一个解决方案,这不需要HTML,只是降价。

 ---
 date: "20 5 2020"
 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))
 ```

 ## Results {.tabset}

 ### 1

 We show a scatter plot in this section.

 ```{r}
 ggplotly(fig)
 ```

 ### 2

 We show the data in this tab.

 ```{r}
 ggplotly(fig)
 ```     
© www.soinside.com 2019 - 2024. All rights reserved.