简体   繁体   中英

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. 在此处输入图片说明

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.

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)

我推荐shinycssloaders软件包及其withSpinner()函数。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM