R语言使用patchwork合并绘图时plot_annotations消失如何修复
问题原因
patchwork 中的plot_annotation是作用于当前顶层拼图对象的属性,当你将两个已添加plot_annotation的patchwork子拼图再次合并时,子拼图的注释属性会被新的顶层拼图忽略,因此不会显示。
解决方案
最简便的解决方式是用wrap_elements()函数将每个已完成注释的子拼图封装为独立的绘图元素,再进行合并,封装后的元素会完整保留原有注释和样式。
修正后代码
library(tidyverse) library(patchwork) # 原有绘图逻辑不变 GG1 = ggplot(iris,aes(x=Sepal.Length,y=Sepal.Width))+ geom_point() GG2 = ggplot(iris,aes(y=Sepal.Length,x=Sepal.Width))+ geom_point() GG3 = ggplot(iris,aes(y=Petal.Width,x=Sepal.Width))+ geom_point() GG4 = ggplot(iris,aes(y=Petal.Length,x=Petal.Width))+ geom_point() combine_1 = GG1 + GG2 + plot_annotation(title = 'Combine plot 1', theme = theme(plot.title = element_text(hjust = 0.5))) combine_2 = GG3 + GG4 + plot_annotation(title = 'Combine plot 2', theme = theme(plot.title = element_text(hjust = 0.5))) # 仅修改合并步骤,用wrap_elements封装两个子拼图 wrap_elements(combine_1) / wrap_elements(combine_2)
可选替代方案
如果仅需要保留子拼图的标题,不需要plot_annotation的其他全局注释属性,也可以直接用ggtitle()给子拼图块加标题,不需要提前设置plot_annotation:
combine_1 = GG1 + GG2 + ggtitle('Combine plot 1') & theme(plot.title = element_text(hjust = 0.5)) combine_2 = GG3 + GG4 + ggtitle('Combine plot 2') & theme(plot.title = element_text(hjust = 0.5)) combine_1 / combine_2
内容的提问来源于stack exchange,提问作者Ed_Gravy
相关产品推荐
相关产品推荐

