I have a function operator to handle plot errors:
library(ggplot2)
library(dplyr)
handle_plot_error <- function(f) {
tryCatch(
f,
error = function(e) plot_error(e)
)
}
plot_error <- function(error) {
ggplot(
tibble(text = str_wrap(error, 80)),
aes(x = 1, y = 1, label = text)
) +
geom_text(color = "red") +
theme_void()
}
I also have a function to create plot facets:
plot_facet <- function(df) {
df %>%
ggplot(aes(cyl, mpg)) +
geom_line() +
facet_grid(~am)
}
It can happen that plot_facet receives an empty dataframe for input:
handle_plot_error(plot_facet(tibble()))
This error doesn't get handled by my function so I would like improve handle_plot_error to include something like:
if(nrow(df) == 0) {
stop("No data available")
}
and then pass this error message to plot_error function.
I know I could include stop case into the plot_facet but I prefer it to be in handle_plot_error since I use it for a lot of plotting functions.
Maybe this can be helpful: https://adv-r.hadley.nz/function-operators.html