ilya
ilya

Reputation: 3164

How to capture ggplot2 errors?

I'm generating pdf reports using ggplot2. Code looks something like this

pdf()
 for (){
   p <- ggplot(..)
   print(p)
 } 
dev.off()

Sometimes because of the data quality ggplot fails to generate the plot. There could be multiple reasons, and we don't want to check all possible combinations for data failing. We simply want to check if ggplot fails - and continue. This is what I came up with - this works, but there are some issues.

library(ggplot2)
p <- ggplot(mtcars, aes(wt, mpg)) +
     geom_point()
p.bad <- ggplot(mtcars, aes(wt, as.character(mpg))) +
  geom_point() +
  scale_y_continuous()

pdf()
a <- try(print(p), silent = TRUE)  # double printing
if (class(a)!='try-error'){
  print(p)
}
b <- try(print(p.bad), silent = TRUE)
if (class(b)!='try-error'){
  print(p.bad)
}
dev.off()

try(print) - generates a chart if there is no error. Is there a way of preventing it? This will probably the best solution. If we do the following - there is no double printing, but second try(print) generates blank page.

pdf()
a <- try(print(p), silent = TRUE)
b <- try(print(p.bad), silent = TRUE)
dev.off()

Is there another way of finding out if ggplot will generate an error?

Upvotes: 0

Views: 373

Answers (1)

Roland
Roland

Reputation: 132969

I suggest to use ggsave:

ttt <- function() {
  require(ggplot2)
  p.bad <- ggplot(mtcars, aes(wt, as.character(mpg))) +
    geom_point() +
    scale_y_continuous()

  a <- try(ggsave("test.pdf",p.bad))
  return("test")
}

ttt()
# Saving 12.9 x 9.58 in image
# Error : Discrete value supplied to continuous scale
# [1] "test"

Upvotes: 2

Related Questions