使用ggarrange组合ggplot图时隐藏子图标题并添加总标题
解决ggarrange组合图时隐藏子图标题的问题
问题说明
已创建两个带标题和副标题的ggplot柱状图(dic_plot_int和jan_plot_int),单独展示时需要保留标题,但使用ggarrange组合成总图时,子图标题导致布局拥挤,希望仅在组合图中隐藏子图标题,只显示统一的总标题,同时询问是否有类似common.legend的标题统一设置方案。
解决方案
方法1:在ggarrange中临时修改子图主题
直接在ggarrange里为每个子图添加theme设置,隐藏标题和副标题,不会修改原始绘图对象,单独调用原始对象时仍会显示标题:
# 组合子图并隐藏子图标题 plot <- ggarrange( dic_plot_int + theme(plot.title = element_blank(), plot.subtitle = element_blank()), jan_plot_int + theme(plot.title = element_blank(), plot.subtitle = element_blank()), ncol = 2, nrow = 1, common.legend = TRUE, legend = "right" ) # 添加统一总标题 annotate_figure(plot, top = text_grob("Indicador de Productividad órdenes Integrales", face = "bold", size = 14))
方法2:批量处理子图(适合多子图场景)
如果需要组合多个子图,可定义批量隐藏标题的函数,避免重复代码:
# 定义函数:移除绘图的标题和副标题 remove_plot_titles <- function(plot_obj) { plot_obj + theme(plot.title = element_blank(), plot.subtitle = element_blank()) } # 应用函数并组合子图 plot <- ggarrange( remove_plot_titles(dic_plot_int), remove_plot_titles(jan_plot_int), ncol = 2, nrow = 1, common.legend = TRUE, legend = "right" ) # 添加统一总标题 annotate_figure(plot, top = text_grob("Indicador de Productividad órdenes Integrales", face = "bold", size = 14))
补充说明
ggarrange目前没有类似common.legend的直接参数来统一隐藏子图标题,但通过上述方法可以满足需求:
- 原始绘图对象的标题完全保留,单独展示时正常显示
- 组合图中仅显示统一设置的总标题,解决布局拥挤问题
内容的提问来源于stack exchange,提问作者Eric Derbez
相关产品推荐
相关产品推荐

