Shiny - custom warning/error messages?

r, shiny

Solution

As we need to return plot to `renderPlot()` we need to display the error/warning within `plot()` function.

We are plotting a blank scatter plot with `"white"` colour, then adding the error message with `text()` function in the middle - `x=1`, `y=1` of the plot, see below working example:

#dummy dataframe
data <- data.frame(sites.id=rep(letters[1:3],10),particles=runif(30))

#subset - change "SiteX" to "a" to test ifelse
data <- data[data$sites.id=="SiteX", ]

if(nrow(data) == 0) {
  # print error/ warning message
  plot(1,1,col="white")
  text(1,1,"no data")
} else {
  # plot the data
  dens <- density(data$particles, na.rm = TRUE)
  plot(dens, main = paste("Histogram of", sites.id, "particles"), 
       xlab = "particles")
}

Problem

How can I print a custom warning/ error message when the required data is empty? for instance, in my server.R, I have this code below, ``` output$plot = renderPlot({ # Sites. site1 = input$site1 # Prepare SQL query. query <- "SELECT * FROM datatable WHERE sites.id = 'SITE1' " # Match the pattern and replace it. query <- sub("SITE1", as.character(site1), query) # Store the result in data. data = dbGetQuery(DB, query) if (is.na(data) || data == '') { # print error/ warning message "sorry, no data is found." } else { # plot the data dens <- density(data$particles, na.rm = TRUE) plot(dens, main = paste("Histogram of ", "particles"), xlab = "particles") } ``` I get this unfriendly red error message below when no data is found. ``` error: need at least 2 points to select a bandwidth automatically ``` ideally, ``` sorry, no data is found. ``` Any ideas?

Original source

Related problems