You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在ggplot与patchwork中避免图例冗余条目?

解决Patchwork组合ggplot图时颜色图例重复的问题

当在其中一张图中添加geom_errorbar后,由于误差棒继承了全局的color映射,会单独生成一个颜色图例条目,和点的图例重复。以下两种方法可以解决这个问题,同时保留size和shape图例:

方法1:仅为点设置颜色映射

将color从全局aes中移到geom_point的aes参数里,这样误差棒不会继承颜色映射,也就不会生成额外的颜色图例:

# 加载数据和包
data("mtcars")
library(ggplot2)
library(patchwork)

ggplot(mtcars,aes(mpg,hp,size = wt)) +
  geom_point(aes(color = factor(am))) +
  
ggplot(mtcars,aes(mpg,hp,shape = factor(gear))) +
  geom_point(aes(color = factor(am))) +
  geom_errorbar(aes(xmin = mpg-(mpg*0.2),
                    xmax =mpg+(mpg*0.2))) +
  plot_layout(guides = "collect")

方法2:隐藏误差棒的图例

保留全局color映射,但在geom_errorbar中设置show.legend = FALSE,让它不生成图例条目:

# 加载数据和包
data("mtcars")
library(ggplot2)
library(patchwork)

ggplot(mtcars,aes(mpg,hp,color = factor(am),size = wt)) +
  geom_point() +
  
ggplot(mtcars,aes(mpg,hp,color = factor(am),shape = factor(gear))) +
  geom_point() +
  geom_errorbar(aes(xmin = mpg-(mpg*0.2),
                    xmax =mpg+(mpg*0.2)), show.legend = FALSE) +
  plot_layout(guides = "collect")

两种方法最终都会只保留一个颜色图例,同时保留size和shape的图例。

内容的提问来源于stack exchange,提问作者Henry Holm

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 01:52:39