添加guides='collect'致patchwork报错:Error in as.unit(value) : object is not coercible to a unit
Patchwork 组合分面图并启用
guides="collect"时触发as.unit(value)报错 问题重现
以下代码原本可正常生成组合图形,但在plot_layout中添加guides = "collect"参数后,触发报错:Error in as.unit(value) : object is not coercible to a unit。
可复现代码
library(tidyverse) library(magrittr) library(patchwork) d1 <- tibble( x = rep(1, 5), y = rep(1, 5), col = letters[1:5] ) p1 <- ggplot( aes(x, y, color = col), data = d1 %>% slice(1:3) ) + facet_wrap(~col, nrow = 1) + geom_point(size = 5) p2 <- ggplot( aes(x, y, color = col), data = d1 %>% slice(4:5) ) + facet_wrap(~col, nrow = 1) + geom_point(size = 5) # 触发报错的代码 p1 / p2 + plot_layout( design = " 111 22# ", guides = "collect" )
报错信息
Error in as.unit(value) : object is not coercible to a unit
环境信息
R version 4.4.1 (2024-06-14 ucrt) Platform: x86_64-w64-mingw32/x64 Running under: Windows 11 x64 (build 26120) Matrix products: default locale: [1] LC_COLLATE=English_United States.utf8 LC_CTYPE=English_United States.utf8 [3] LC_MONETARY=English_United States.utf8 LC_NUMERIC=C [5] LC_TIME=English_United States.utf8 time zone: Australia/Sydney tzcode source: internal attached base packages: [1] stats graphics grDevices utils datasets methods base other attached packages: [1] patchwork_1.2.0 magrittr_2.0.3 lubridate_1.9.3 forcats_1.0.0 stringr_1.5.1.9000 [6] dplyr_1.1.4 purrr_1.0.2.9000 readr_2.1.5 tidyr_1.3.1 tibble_3.2.1 [11] ggplot2_3.5.1.9000 tidyverse_2.0.0.9000 loaded via a namespace (and not attached): [1] vctrs_0.6.5 cli_3.6.3 rlang_1.1.4 stringi_1.8.4 generics_0.1.3 [6] labeling_0.4.3 glue_1.7.0 colorspace_2.1-1 hms_1.1.3 scales_1.3.0 [11] fansi_1.0.6 grid_4.4.1 munsell_0.5.1 tzdb_0.4.0 lifecycle_1.0.4 [16] compiler_4.4.1 timechange_0.3.0 pkgconfig_2.0.3 rstudioapi_0.16.0 farver_2.1.2 [21] R6_2.5.1 tidyselect_1.2.1 utf8_1.2.4 pillar_1.9.0 tools_4.4.1 [26] withr_3.0.1 gtable_0.3.5
解决方案
这个报错源于patchwork在收集分面图的图例时,与自定义布局中的占位符#存在兼容性冲突。可以通过以下两种方式解决:
方案1:移除布局占位符,使用默认布局收集图例
如果不需要保留占位符的空白区域,直接移除design参数或调整为无占位符的设计即可:
p1 / p2 + plot_layout(guides = "collect")
方案2:手动分离图例,自定义布局放置
先移除子图的图例,单独创建图例区域,再通过design参数指定布局位置:
# 移除子图的图例 p1_no_guide <- p1 + theme(legend.position = "none") p2_no_guide <- p2 + theme(legend.position = "none") # 组合子图与图例区域 combined <- p1_no_guide / p2_no_guide + guide_area() # 指定布局,用3代表图例区域 combined + plot_layout(design = " 111 223 ")
内容的提问来源于stack exchange,提问作者tomw
相关产品推荐
相关产品推荐

