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

R语言patchwork绘图:图例合并与轴标签显示问题

问题解决:Patchwork组合多图的图例合并与轴标签控制

需求说明

使用patchwork包组合3个ggplot对象,需实现:

  • 合并所有子图的图例为一个;
  • 仅显示中间子图的y轴标签、底部子图的x轴标签。

解决方案

1. 合并所有图例

三个子图的颜色渐变参数完全一致,但单独定义时patchwork可能无法识别为同一图例。推荐将公共的颜色刻度和主题提取出来统一应用,确保所有子图共享同一scale,再通过plot_layout(guides = "collect")完成合并。

2. 控制轴标签显示

针对每个子图单独设置轴标签的显示状态:

  • 顶部子图:隐藏x轴和y轴标签;
  • 中间子图:保留y轴标签,隐藏x轴标签;
  • 底部子图:保留x轴标签,隐藏y轴标签。

修改后的完整代码

# 加载依赖包
library(ggplot2)
library(patchwork)
library(scales)

# 定义公共主题与颜色刻度,避免重复代码
common_theme <- theme_classic(base_size = 20) +
  theme(plot.title = element_text(hjust = 0.5)) # 可选:让标题居中

common_colour_scale <- scale_colour_gradient(
  low = 'blue', 
  high = 'red',
  name = "Time after \nplating (h)"
)

# 顶部子图:阳极
MEAN_an <- ggplot(anode_50, aes(x = tau, y = mean, group = t))+
  geom_path(aes(colour = t))+
  labs(
    x = NULL, 
    y = NULL, 
    title = "Cu-LFP cell 16 \n 0.5 mAh/cm2"
  )+
  scale_x_continuous(
    limits = c(10^-6, 10^0),
    trans = 'log10',
    breaks=trans_breaks('log10', function(x) 10^x),
    labels=trans_format('log10', math_format(10^.x))
  )+
  ylim(0,75)+
  common_theme +
  common_colour_scale +
  theme(legend.position = "none") # 隐藏该子图图例

# 中间子图:阴极
MEAN_cath <- ggplot(cath_50, aes(x = tau, y = mean, group = t))+
  geom_path(aes(colour = t))+
  labs(
    x = NULL, 
    y = bquote(gamma*"ln"(tau)(~Omega~ "cm"^2)),
    title = "Cu-LFP cell 16 \n 0.5 mAh/cm2"
  )+
  scale_x_continuous(
    limits = c(10^-6, 10^0),
    trans = 'log10',
    breaks=trans_breaks('log10', function(x) 10^x),
    labels=trans_format('log10', math_format(10^.x))
  )+
  ylim(0,50)+
  common_theme +
  common_colour_scale +
  theme(legend.position = "none") # 隐藏该子图图例

# 底部子图:全电池
MEAN_full <- ggplot(full_50, aes(x = tau, y = mean, group = t))+
  geom_path(aes(colour = t))+
  labs(
    x = bquote(tau*" (s)"),
    y = NULL, 
    title = "Cu-LFP cell 16 \n 0.5 mAh/cm2"
  )+
  scale_x_continuous(
    limits = c(10^-6, 10^0),
    trans = 'log10',
    breaks=trans_breaks('log10', function(x) 10^x),
    labels=trans_format('log10', math_format(10^.x))
  )+
  ylim(0,50)+
  common_theme +
  common_colour_scale # 保留该子图图例用于合并

# 组合图形并合并图例
comb <- MEAN_an / MEAN_cath / MEAN_full +
  plot_layout(guides = 'collect')

comb

关键说明

  • 提取公共主题和颜色刻度,既减少重复代码,又确保所有子图使用同一图例规则,plot_layout(guides = 'collect')可直接合并为单个图例;
  • 通过labs(x = NULL, y = NULL)快速控制轴标签显示,也可使用theme(axis.title.x = element_blank())实现相同效果;
  • 仅保留底部子图的图例,其余子图隐藏,避免合并后出现冗余图例。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 20:21:08