Prashanth kumar
Prashanth kumar

Reputation: 985

Shiny R - ggplotly - Show custom message instead of empty plot when the dataset does not return any information

The shiny application I'm working on is displaying graphs using ggplotly. In an instance when the resulting dataset is empty, a blank plot is being displayed, as below. enter image description here

Is it possible to show a custom message such as "No data exists with the selected inputs" instead of an empty plot

With the help of validate, need I am able to display the error message when the user does not select input in the front-end -

validate(
      need(input$category, 'No data exists, please select a Category')
      )



I would like to display a custom message similarly in the server side when the final dataset is empty, I've tried below codes so far as per the help from google. These codes aren't giving any errors, but the error message is being print by default.

validate(
    need(nrow(dataset() > 0), 'Message here')
    )

or

validate(
    need(is.null(dataset), 'Message here')
    )



I am plotting with the help of below code, where g() is my final dataset after filter applied basis user input -

output$plot1 <- renderPlotly({
    p <- ggplot(g(), aes_string(x=input$x, y=input$y)) + geom_point(alpha=0.4)
    ggplotly(p)

  })

I am new to Shiny and R, any help is appreciated.

Thanks.

Upvotes: 8

Views: 2665

Answers (2)

Pork Chop
Pork Chop

Reputation: 29387

Something like this?

library(shiny)
library(plotly)

ui <- fluidPage(
  plotlyOutput("plot")
)

server <- function(input, output) {

  g <- reactive({NULL})

  output$plot <- renderPlotly({
    validate(
      # Old Code
      need(nrow(g() > 0), 'No data exists, please select a Category')
      # With parentheses fix
      need(nrow(g()) > 0, 'No data exists, please select a Category')
    )
    plot_ly(g(), x = ~mpg, y = ~wt)
  })
}

shinyApp(ui, server)

Upvotes: 8

Łukasz Prokulski
Łukasz Prokulski

Reputation: 79

I recommend shinycssloaders package and its withSpinner() function.

Upvotes: 0

Related Questions