How to display ggplotly plots with dynamically created tabs and for-loops?

可紊 提交于 2021-01-27 20:03:27

问题


I have R markdown document and I want to dynamically create tabs with ggplotly graphics inside them

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

I understand that it is different from normal ggplot graph and I looked at the solutions here: enter link description here but It did not work for me


回答1:


Following this post this can be achieved like so:

Edit: Following this post I added two functions to pass the fig.width and fig.height to ggplotly.

Edit 2: Added the code to additionally use plotly::subplots.

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



回答2:


found a solution from this link too, this doesn't call for HTML, just markdown.

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


来源:https://stackoverflow.com/questions/61906480/how-to-display-ggplotly-plots-with-dynamically-created-tabs-and-for-loops

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!