ggplot2多图合并时theme(legend.position='top')致图例重复问题
解决ggplot合并图重复图例问题
问题根源
你使用& theme(legend.position = "top")时,该语句会全局覆盖所有子图的主题设置,包括子图b的theme(legend.position = "none"),导致b图原本隐藏的图例重新显示。而plot_layout(guides = "collect")会收集两个子图的图例,最终出现重复。
解决方法
方法1:用guides()移除子图b的图例(推荐)
直接移除子图b中不需要的图例对象,而非仅隐藏图例区域,这样collect时只会收集到子图a的图例,再全局设置图例位置即可:
# 加载依赖包 library(ggplot2) library(patchwork) # 虚拟数据(来自原问题) set.seed(123) df <- data.frame( group = rep(c("A", "B", "C"), each = 10), x = rnorm(30), y = rnorm(30), category = rep(c("X", "Y"), 15) ) # 子图a:柱状图,保留图例 a <- ggplot(df, aes(x = group, y = y, fill = category)) + geom_col(position = "dodge") # 子图b:散点图,直接移除图例 b <- ggplot(df, aes(x = x, y = y, color = category)) + geom_point() + guides(color = "none") # 彻底移除color图例,而非仅隐藏 # 组合图:收集图例并设置顶部位置 a + b + plot_annotation(tag_levels = 'a') + plot_layout(guides = "collect") & theme(legend.position = "top")
方法2:保留子图主题设置,不全局覆盖图例位置
如果要保留子图a的theme(legend.position = "top")和子图b的theme(legend.position = "none"),组合时不要添加& theme(legend.position = "top"),collect会自动保留子图a的图例位置:
# 子图a:设置图例在顶部 a <- ggplot(df, aes(x = group, y = y, fill = category)) + geom_col(position = "dodge") + theme(legend.position = "top") # 子图b:隐藏图例区域 b <- ggplot(df, aes(x = x, y = y, color = category)) + geom_point() + theme(legend.position = "none") # 组合图:仅收集图例,不全局设置主题 a + b + plot_annotation(tag_levels = 'a') + plot_layout(guides = "collect")
以上两种方法都能实现合并后仅显示一个顶部图例的效果。
内容的提问来源于stack exchange,提问作者hnguyen
相关产品推荐
相关产品推荐

