I'm producing daily powerpoint slidedecks from raw Covid case data, and today, we have no cases! Excellent, except it broke my reports :-(
I generate ggplots, and place them on powerpoint slides using officer. The ggplot errors only arise when it is evaluated by officer, inside the slide creation pipeline.
I could catch the errors upstream, but doing it right before slide generation makes the code nicer, because the slide generation process is many layered, and it would be good to be able to continue to produce the artifact despite the error.
Reprex follows:
Note, the error does not occur in R 3.6, probably due to a change in the way scale_x_discrete evaluates labels, but it would still be good to have a general way to fail gracefully
library( stringr )
library(ggplot2)
library(officer)
data = structure(list(LGA = character(0), Sex = character(0)), row.names = integer(0), class = c("tbl_df",
"tbl", "data.frame"))
plot = ggplot( data, aes( LGA, Sex ) ) +
geom_point() +
scale_x_discrete(labels = function(x) str_wrap(x, width = 15))
read_pptx() %>%
add_slide( ) %>%
ph_with( plot, location=ph_location_type() )
#> Warning in rep(yes, length.out = len): 'x' is NULL so the result will be NULL
#> Error in ans[ypos] <- rep(yes, length.out = len)[ypos]: replacement has length zero
Created on 2021-01-19 by the reprex package (v0.3.0)
It seems that I should be able to use purrr::possibly to catch the error, but it expects a function:
Error: Can't convert a `gg/ggplot` object to function
Note: eliminated second example
Sessioninfo below:
> sessionInfo()
R version 4.0.3 (2020-10-10)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows Server x64 (build 14393)
Matrix products: default
locale:
[1] LC_COLLATE=English_Australia.1252 LC_CTYPE=English_Australia.1252
[3] LC_MONETARY=English_Australia.1252 LC_NUMERIC=C
[5] LC_TIME=English_Australia.1252
attached base packages:
[1] stats graphics grDevices utils datasets methods base
other attached packages:
[1] purrr_0.3.4 officer_0.3.15 ggplot2_3.3.3 stringr_1.4.0
[5] nvimcom_0.9-92.3
loaded via a namespace (and not attached):
[1] xml2_1.3.2 magrittr_2.0.1 tidyselect_1.1.0 munsell_0.5.0
[5] uuid_0.1-4 colorspace_1.4-1 R6_2.5.0 rlang_0.4.8
[9] dplyr_1.0.2 tools_4.0.3 grid_4.0.3 gtable_0.3.0
[13] withr_2.3.0 ellipsis_0.3.1 tibble_3.0.4 lifecycle_0.2.0
[17] crayon_1.3.4 zip_2.1.1 vctrs_0.3.4 glue_1.4.2
[21] stringi_1.5.3 compiler_4.0.3 pillar_1.4.6 generics_0.1.0
[25] scales_1.1.1 pkgconfig_2.0.3
>
The error happens when the plot is built by ggplot_build()
. Normally you don't call this directly, it's called by the functions that display the object, but you can call it yourself. For example,
if (inherits(try(ggplot_build(plot)), "try-error"))
plot <- ggplot()
will replace a bad plot by a blank one.