I am trying to implement an option with a drop-down menu in a simple Shiny application. With this drop-down list, you can choose between two charts. The first chart is prepared with the ggplot2
library, while the second is with the Plotly
library. Below you can see my code :
---
title: "Test App"
output:
flexdashboard::flex_dashboard:
orientation: columns
vertical_layout: fill
runtime: shiny
---
```{r setup, include=FALSE}
library(flexdashboard)
library(shiny)
library(tidyverse)
library(plotly)
# Data
data <- mtcars
data$cyl <- as.factor(data$cyl)
```
Column {.sidebar}
-----------------------------------------------------------------------
```{r}
selectInput("clusterNum",
label = h4("Charts"),
choices = list("Chart1" = "Chart1", "Chart2" = "Chart2"),
selected = "Chart1"
)
```
Column {data-width=650}
-----------------------------------------------------------------------
### Chart
```{r}
Chart1 <- ggplot(data, aes(x = wt, y = mpg)) +
geom_point()
Chart2 <- plot_ly(data, x = ~wt, y = ~mpg, type = 'bar')
renderPlot({
switch(input$clusterNum,
"Chart1" = Chart1,
"Chart2" = Chart2
)
})
```
After executing this code, I saw that Chart 1, which was prepared with ggplot2, works well, while Chart 2 with Plotly is not displayed. So can anybody help me how to solve this problem and to see Chart 2 after selection with the drop-down list?
>Solution :
To render the plotly
chart you have to use renderPlotly
, while for the ggplot we have to stick with renderPlot
. As a consequence switching conditionally between the two render functions requires some more effort and involves wrapping in renderUI
and displaying the chart via uiOutput
:
---
title: "Test App"
output:
flexdashboard::flex_dashboard:
orientation: columns
vertical_layout: fill
runtime: shiny
---
```{r setup, include=FALSE}
library(flexdashboard)
library(shiny)
library(tidyverse)
library(plotly)
# Data
data <- mtcars
data$cyl <- as.factor(data$cyl)
```
Column {.sidebar}
-----------------------------------------------------------------------
```{r}
selectInput("clusterNum",
label = h4("Charts"),
choices = list("Chart1" = "Chart1", "Chart2" = "Chart2"),
selected = "Chart1"
)
```
Column {data-width=650}
-----------------------------------------------------------------------
### Chart
```{r}
Chart1 <- ggplot(data, aes(x = wt, y = mpg)) +
geom_point()
Chart2 <- plot_ly(data, x = ~wt, y = ~mpg, type = 'bar')
```
```{r}
observeEvent(input$clusterNum, {
output$plot <- switch(input$clusterNum,
"Chart1" = renderUI({renderPlot(Chart1)}),
"Chart2" = renderUI({renderPlotly(Chart2)})
)
})
uiOutput("plot")
```