yuliaUU
yuliaUU

Reputation: 1713

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

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

Upvotes: 3

Views: 3395

Answers (2)

stefan
stefan

Reputation: 124473

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

Upvotes: 6

Daniel_j_iii
Daniel_j_iii

Reputation: 3252

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

Upvotes: -2

Related Questions