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

如何在Matplotlib中沿X轴裁剪图形并保留比例以对比时序图

解决Matplotlib时序图长度与时间范围成比例的问题

情况1:多个子图并排对比

如果要把不同时间范围的图放在同一画布的子图里,直接通过width_ratios参数控制子图宽度比例,让宽度和时间跨度成正比:

  1. 先计算各案例的时间跨度比例,比如5秒、10秒、30秒的比例是1:2:6(以最小跨度5秒为基准)
  2. 创建子图时用gridspec_kw传入比例参数

示例代码:

import matplotlib.pyplot as plt
import numpy as np

# 模拟数据
t_5s = np.linspace(0, 5, 100)
y_5s = np.sin(t_5s)

t_10s = np.linspace(0, 10, 200)
y_10s = np.cos(t_10s)

t_30s = np.linspace(0, 30, 600)
y_30s = np.tanh(t_30s/5)

# 定义时间跨度和宽度比例
time_spans = [5, 10, 30]
base_span = min(time_spans)
width_ratios = [span / base_span for span in time_spans]

# 创建带宽度比例的子图
fig, axes = plt.subplots(nrows=1, ncols=3, figsize=(12, 4), gridspec_kw={'width_ratios': width_ratios})

# 绘制每个子图并固定x轴范围
axes[0].plot(t_5s, y_5s)
axes[0].set_xlim(0, 5)
axes[0].set_title('5秒')

axes[1].plot(t_10s, y_10s)
axes[1].set_xlim(0, 10)
axes[1].set_title('10秒')

axes[2].plot(t_30s, y_30s)
axes[2].set_xlim(0, 30)
axes[2].set_title('30秒')

plt.tight_layout()
plt.show()

这样每个子图的宽度会严格按照时间跨度的比例分配,5秒的图宽度正好是30秒图的1/6,且不会有多余空白。

情况2:单独生成每张图

如果是单独保存每张图,直接根据时间跨度设置画布的figsize宽度,同时用bbox_inches='tight'裁剪空白:

比如30秒的图设置宽度为12,5秒的图宽度就设为12*(5/30)=2,保持高度一致:

# 生成5秒的图
fig, ax = plt.subplots(figsize=(2, 4))
ax.plot(t_5s, y_5s)
ax.set_xlim(0, 5)
plt.tight_layout()
plt.savefig('5s_plot.png', bbox_inches='tight')

# 生成30秒的图
fig, ax = plt.subplots(figsize=(12, 4))
ax.plot(t_30s, y_30s)
ax.set_xlim(0, 30)
plt.tight_layout()
plt.savefig('30s_plot.png', bbox_inches='tight')

保存后的两张图宽度比例正好是1:6,完全匹配时间范围的比例,且没有多余空白区域。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 21:40:23