Shiny: Replace renderPlotly errors with some text description or default plot

Viewed 210

I am creating a Shiny App and I want to use the brush function. The app currently looks like:

enter image description here

Where in the one box() I get the error Error: argument 1 is not a vector. This error disappears when the user makes a brushed selection of the plot.

enter image description here

How can I mask the error into a more user friendly description such as "Please select an area of the above plot in order to generate this window...".

The plot box() is supposed to plot the user selection such as a zoom-in version of the plot.

Code:

data <- mtcars



library(shiny)
library(shinydashboard)

header <- dashboardHeader(title = "My Dashboard")
sidebar <- dashboardSidebar(
    sidebarMenu(
        menuItem(text = "Main Menu", tabName = "MainPage")
    )
)
body <- dashboardBody(
    tabItems(
        tabItem(tabName = "MainPage",
                fluidRow(
                    box(
                        width = 12,
                        plotOutput("myPlot1", brush = "userSelectedSummaryStatistics")
                    )
                ),
                fluidRow(
                    box(
                        width = 4,
                        DT::dataTableOutput("userDefinedTable")
                    ),
                    box(
                        width = 8,
                        plotlyOutput("selectedUserDataFromUserDefinedTable")
                    )
                )
        )
    )
)


ui <- dashboardPage(
    header, sidebar, body
)

server <- function(input, output, session){
    output$myPlot1 <- renderPlot({
        data %>% 
            ggplot(aes(x = mpg, y = disp)) +
            geom_line()
    })
    
    selectedUserData = reactive({
        userSelectedSummaryStatistics = input$userSelectedSummaryStatistics
        userSelection = brushedPoints(data, userSelectedSummaryStatistics)
        return(userSelection)
    })
    
    output$userDefinedTable = DT::renderDataTable(DT::datatable(selectedUserData()))
    
    output$selectedUserDataFromUserDefinedTable <- renderPlotly({
        ggplotly(
            selectedUserData() %>% 
                ggplot(aes(x = mpg, y = disp)) +
                geom_line()
        )
    })
}


shinyApp(ui, server)
1 Answers

You can use validate:

  output$selectedUserDataFromUserDefinedTable <- renderPlotly({
    validate(need(nrow(selectedUserData())>0,'Please select an area of the above plot in order to generate this window'))
    ggplotly(
      selectedUserData() %>% 
        ggplot(aes(x = mpg, y = disp)) +
        geom_line()
    )
  })

enter image description here

Related