Search code examples
rshinyr-markdownggplotly

How can I prevent overlapping plotly graphs in a shiny Rmd?


Given a shiny r-markdown report with reactive plotly plots, how do I prevent long plots (produced with ggplotly) from overlapping?

In the example it is evident that the plot produced in the plotly-long chunk is overlapped by the plot produced in the chunk below.

---
title: "A shiny Report"
runtime: shiny
output:
  bookdown::html_document2
---

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

library(tidyverse)
library(plotly)

df <- data.frame(type =  c("potato", "carrot", "leek"),
                 count = c(1, 3, 2))
```

```{r, results="asis"}
selectizeInput("SELECTION",
               "Choose:",
               selected = c("potato", "leek"),
               multiple = TRUE,
               choices = c("potato", "carrot", "leek"))
```

```{r, filter-data}
df_filt <- reactive({
  df %>%
    filter(type %in% input$SELECTION)
})
```

```{r make-ggplot}
ggp <- reactive({
  df_filt() %>%
    ggplot(aes(y = count, fill = type, x = "a_bar")) +
    geom_bar(stat = "identity")
})
```

```{r plotly-long}
renderPlotly({
  ggplotly(ggp(), height = 1600)
})
```

```{r plotly-normal}
renderPlotly({
  ggplotly(ggp())
})
```

Solution

  • Replacing renderPlotly with renderUI does the trick.

    ---
    title: "A shiny Report"
    runtime: shiny
    output:
      bookdown::html_document2
    ---
    
    ```{r setup, include=FALSE}
    knitr::opts_chunk$set(echo = FALSE)
    
    library(tidyverse)
    library(plotly)
    
    df <- data.frame(type =  c("potato", "carrot", "leek"),
                     count = c(1, 3, 2))
    ```
    
    ```{r, results="asis"}
    selectizeInput("SELECTION",
                   "Choose:",
                   selected = c("potato", "leek"),
                   multiple = TRUE,
                   choices = c("potato", "carrot", "leek"))
    ```
    
    ```{r, filter-data}
    df_filt <- reactive({
      df %>%
        filter(type %in% input$SELECTION)
    })
    ```
    
    ```{r make-ggplot}
    ggp <- reactive({
      df_filt() %>%
        ggplot(aes(y = count, fill = type, x = "a_bar")) +
        geom_bar(stat = "identity")
    })
    ```
    
    ```{r plotly-long}
    renderUI({
      ggplotly(ggp(), height = 1600)
    })
    ```
    
    ```{r plotly-normal}
    renderUI({
      ggplotly(ggp())
    })
    ```