r - 如何在管道中评估ggplot对象时发生错误?

标签 r ggplot2 error-handling purrr officer

我每天从原始Covid案例数据中生成PowerPoint幻灯片,而今天,我们还没有案例!很好,除了它破坏了我的报告:-(
我生成了ggplots,并使用Officer将它们放置在PowerPoint幻灯片上。 ggplot错误仅在幻灯片创建管道内的人员评估时出现。
我可以在上游捕获错误,但是在幻灯片生成之前立即进行操作会使代码更好,因为幻灯片生成过程是多层的,即使出现错误,也能够继续生成 Artifact 是很好的。
Reprex如下:
请注意,在R 3.6中不会发生该错误,这可能是由于scale_x_discrete评估标签的方式发生了变化,但是最好有一种一般的方式来正常地失败


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
reprex package(v0.3.0)创建于2021-01-19
看来我应该能够使用purrr::可能捕获错误,但是它需要一个函数:
Error: Can't convert a `gg/ggplot` object to function
注意:取消第二个例子
Sessioninfo如下:

> 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
>

最佳答案

当通过ggplot_build()构建图时,将发生错误。通常,您不直接调用此函数,它由显示对象的函数调用,但是您可以自己调用它。例如,

if (inherits(try(ggplot_build(plot)), "try-error")) 
  plot <- ggplot()
将空白处替换为坏处。

关于r - 如何在管道中评估ggplot对象时发生错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65783706/

相关文章:

r - 在 Shiny 中使用多个条目对数据集进行子集化会产生不正确的输出

regex - R 正则表达式和聚合/子集

r - 如何在ggplot的箱线图中显示中值?

r - ggplot2:从包含geom_histogram的绘图对象读取最大条形高度

forms - Dojo dijit.form.Select验证错误显示

error-handling - 在java 8流foreach中抛出异常

r - knitr 生成 pdf 输出文件

r - 正确使用以下函数 :describeBy, statsBy, and stat.desc

r - 如何让 ggplot 正确排序构面?

error-handling - 解析错误代码154