1

I'm working on a larger shiny app that lets the user input data. One option is to plot a histogram and to have coordinate transformations. There is an error that occurs when a log transformation is applied to a histogram that has a bin that touches zero.

I know what is causing the error, but can't seem to figure out how to catch the error. Ideally I'd like to send a message to the user to try a different transformation (e.g., psuedo-log), but I can't figure out where to put a tryCatch function or similar error catching code.

In the example code attached, I tried putting a tryCatch around the ggplot call in server and the plotOutput call in ui. Even running just the ggplot line by itself (second code section), I haven't figured out how to catch the error.

library(shiny)
library(tidyverse)
library(scales)

transforms <- list("None" = identity_trans(),
                    "Log 10" = log10_trans()
                    )
                    
ui <- fluidPage(

  titlePanel("Old Faithful Geyser Data"),
  
  sidebarLayout(
    sidebarPanel(
      selectInput("Xaxis",
                  "Choose X axis transformation:",
                  names(transforms)
                  )
    ),
    mainPanel(
      plotOutput("distPlot")
    )
  
  )
)

server <- function(input, output){

  output$distPlot <- renderPlot({
    ggplot(diamonds, aes(x=z)) + geom_histogram() + coord_trans(x=transforms[[input$Xaxis]])
  })
}

shinyApp(ui=ui, server=server)
gg <- ggplot(diamonds, aes(x=z)) + geom_histogram() + coord_trans(x="log10")

tryCatch({
  gg
}, error = function(e){
  print("Error")
  return()
})

fish_dots
  • 118
  • 10

1 Answers1

0

Rather than just gg in your tryCatch, you need print(gg)

tryCatch({
  print(gg)
}, error = function(e){
  print("Error")
  return()
})

The plot isn't built until it's actually printed.

MrFlick
  • 195,160
  • 17
  • 277
  • 295
  • My problem appears to be having a slightly older version of R (4.0.5), in which I had previously tried the print(gg) method and it didn't work. Adding the print statement works as anticipated on a newer version of R. – fish_dots Aug 15 '22 at 12:07