Description
I run a complex Shiny App which has to display either a "normal" plot Output with renderPlot
, or a plotly plot with renderPlotly
, based on the input values that are selected. For this reason, I need to be able to send NULL
to renderPlotly
if the plotly plot is not needed at this time. This renders an error at the moment, while renderPlot
does not.
To give you an illustration:
library(shiny)
library(plotly)
ui <- fluidPage(
actionButton("action", label = "Action!"),
plotlyOutput("plotly")
)
server <- function(input, output) {
act <- reactive({
if (input$action > 0)
TRUE
else
FALSE
})
output$plotly <- renderPlotly(
if (act()) {
ggplot(mtcars, aes(cyl, mpg)) + geom_point()
} else {
NULL
}
)
}
shinyApp(ui, server)
The following code has only a pressable button and, after this button is pressed, a plotly output. Before I press the button, I get an error from renderPlotly()
because it has to deal with a NULL value.
At the moment, there are two main ways to workaround this:
Method 1
Replace the NULL with plotly_empty()
. The error disappears, but this slows down my Shiny App, because there always has to be an empty plot which has to be rendered, and displayed. Also, this plot is rendered even when other plots which have to be displayed are rendered at the same time.
Method 2
Wrap the plotlyOutput()
function into a renderUI()
at the server side, so the plot is only displayed when the right conditions are met (in our case act()
being TRUE
). This solves the problem of displaying something which is empty, but still doesn't solve the problem that renderPlotly()
renders an empty plot all the time.
So to summarise, it would be cool if renderPlotly()
supported NULL values and then just did nothing rendering an error.