Search code examples
ggplot2shinyplotlyflexdashboardggplotly

Flexdashboard not able to render ggplotly and ggplot object on same markdown


I have a basic reproducible example here that I think might just be a package limitation. I was wondering if I am just doing something wrong? They both plot fine separately but when combined in the same markdown make the dashboard unable to correctly render.

---
title: "Untitled"
output: 
  flexdashboard::flex_dashboard:
    orientation: rows
    source_code: embed
runtime: shiny
---

```{r setup, include=FALSE}
library(tidyverse)
library(plotly)
library(albersusa)

state_sf <- usa_sf("aeqd")

state_dat <- data.frame(state = c("Washington", "Wyoming","Texas","California"), pct = c(0.3,0.5,0.8,0.1))

state_map <- state_sf %>% 
  left_join(state_dat, by = c("name" = "state"))
```

Test
===================================== 

Sidebar {.sidebar data-width=200}
-------------------------------------

Testing

Row
-----------------------------------------------------------------------

###Plotly

```{r graph 1, fig.height=4, fig.width=6}
#Symptoms by state last week===================================================
ggplotly(
  ggplot(data = state_map) + 
    geom_sf(aes(fill=pct))
)
```

###Bar

```{r graph 2, fig.height=4, fig.width=3}
ggplot(data=state_dat) +
  geom_col(aes(state,pct,fill=pct)) 
```

Solution

  • If you are using runtime: shiny you need to use the proper type of Shiny's renderX() functions for each type of plot object to display properly. I don't know why only one plot chunk (w/o renderX()) works, but two breaks it.

    ### Plotly
    
    ```{r graph_1, fig.height=4, fig.width=3}
    #Symptoms by state last week
    renderPlotly({
      ggplotly(
        ggplot(data = state_map) + 
        geom_sf(aes(fill=pct))
      )
    })
    ```
    
    ### Bar
    
    ```{r graph_2, fig.height=4, fig.width=3}
    renderPlot({
      ggplot(data=state_dat) +
        geom_col(aes(state,pct,fill=pct))
    })
    ```