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

如何在R的patchwork布局中删除inset小图图例并保留主图图例

解决patchwork布局中inset小图图例被全局主题覆盖的问题

问题出在你最后一行的全局主题设置 & theme(legend.position = c(0.9, 0.15)) —— 这个语法会将主题应用于所有子图,包括你创建的两个inset小图,直接覆盖了你之前给小图设置的theme(legend.position = "none"),导致小图依然显示图例。

要解决这个问题,只需把主图的图例位置设置单独应用到主图上,而非用全局的&统一设置,这样inset小图的隐藏图例设置就能正常生效。

修改后的完整代码如下:

library(patchwork)
library(ggplot2)
data(mtcars)

######## Plot 1
plot1 <- ggplot(mtcars, aes(x = hp, y = mpg, color = factor(cyl))) +
  geom_point() +
  labs(title = "Plot 1") +
  theme(legend.position = c(0.9, 0.15))  # 仅给主图设置图例位置

inset.plot1 <- ggplot(mtcars, aes(x = wt, y = qsec, color = factor(gear))) +
  geom_point() +
  theme(legend.position = "none") +  # 小图隐藏图例
  labs(title = "inset Plot 1")

layout.plot1 <- plot1 + 
  inset_element(inset.plot1, 
                left=0.7, bottom=0.7, right=1, top=1)

####### Plot 2
plot2 <- ggplot(mtcars, aes(x = disp, y = drat, color = factor(carb))) +
  geom_point() +
  labs(title = "Plot 2") +
  theme(legend.position = c(0.9, 0.15))  # 仅给主图设置图例位置

inset.plot2 <- ggplot(mtcars, aes(x = hp, y = wt, color = factor(am))) +
  geom_point() +
  theme(legend.position = "none") +  # 小图隐藏图例
  labs(title = "Inset Plot 2")

layout.plot2 <- plot2 + 
  inset_element(inset.plot2, 
                left=0.7, bottom=0.7, right=1, top=1)


####### Final layout
Final.layout <- 
  layout.plot1 + layout.plot2 +
  plot_layout(guides = "keep")

这样修改后,主图会保留位于指定位置的图例,而两个inset小图则不会显示图例,完全符合你的需求。

内容的提问来源于stack exchange,提问作者Giuseppe Petri

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 07:20:06