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

如何用Matplotlib读取多列.dat文件并绘制带/无间距的子图

解决Matplotlib多子图绘图需求

我来帮你搞定这个绘图需求!咱们先优化数据读取的逻辑,再用Matplotlib的子图功能实现你要的两种布局效果。

1. 简化数据读取

你的逐行读取代码可以换成numpy的loadtxt函数,它能直接读取整个数据文件,还能自动跳过注释行,效率更高:

import numpy as np
import matplotlib.pyplot as plt

# 读取sigma.dat,自动跳过#、@开头的注释行
data = np.loadtxt("sigma.dat", comments=['#', '@'])
# 提取x轴数据(第一列)
x = data[:, 0]
# 分组提取y轴数据:第一组是列1、列2,第二组是列3、列4
y1_group = data[:, 1:3]
y2_group = data[:, 3:5]

2. 生成带间距的子图

创建2行1列的子图布局,设置sharex=True让两个子图共享x轴,再通过hspace参数设置子图间的垂直间距:

# 创建带间距的2行1列子图,共享x轴
fig, (ax_top, ax_bottom) = plt.subplots(nrows=2, ncols=1, figsize=(8, 10), sharex=True, hspace=0.3)

# 绘制上方子图(列0-1-2)
ax_top.plot(x, y1_group[:, 0], label='Column 1')
ax_top.plot(x, y1_group[:, 1], label='Column 2')
ax_top.set_title('Group 1: Columns 0-1-2')
ax_top.set_ylabel('Values')
ax_top.legend()

# 绘制下方子图(列0-3-4)
ax_bottom.plot(x, y2_group[:, 0], label='Column 3')
ax_bottom.plot(x, y2_group[:, 1], label='Column 4')
ax_bottom.set_title('Group 2: Columns 0-3-4')
ax_bottom.set_xlabel('X-axis')
ax_bottom.set_ylabel('Values')
ax_bottom.legend()

# 保存带间距的图片
plt.savefig("sigma_with_spacing.png", dpi=300)
plt.close()

这里的hspace=0.3控制了子图间的间距,数值越大,间距越宽。

3. 生成无间距的子图

只需要把hspace设为0,再隐藏上方子图的x轴刻度,避免两个子图的刻度重叠:

# 创建无间距的2行1列子图,共享x轴
fig, (ax_top, ax_bottom) = plt.subplots(nrows=2, ncols=1, figsize=(8, 10), sharex=True, hspace=0)

# 绘制上方子图
ax_top.plot(x, y1_group[:, 0], label='Column 1')
ax_top.plot(x, y1_group[:, 1], label='Column 2')
ax_top.set_title('Group 1: Columns 0-1-2')
ax_top.set_ylabel('Values')
ax_top.legend()
# 隐藏上方子图的x轴刻度,避免和下方子图重叠
ax_top.tick_params(axis='x', which='both', bottom=False, labelbottom=False)

# 绘制下方子图
ax_bottom.plot(x, y2_group[:, 0], label='Column 3')
ax_bottom.plot(x, y2_group[:, 1], label='Column 4')
ax_bottom.set_title('Group 2: Columns 0-3-4')
ax_bottom.set_xlabel('X-axis')
ax_bottom.set_ylabel('Values')
ax_bottom.legend()

# 保存无间距的图片
plt.savefig("sigma_no_spacing.png", dpi=300)
plt.close()

设置hspace=0后,两个子图会紧密贴合,加上tick_params隐藏刻度,整体布局会更整洁。

小提示

  • sharex=True能让两个子图的x轴范围完全同步,还能减少重复的x轴标签,提升可读性。
  • 如果你的sigma.dat里没有注释行,loadtxt可以直接省略comments参数,用np.loadtxt("sigma.dat")就行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 07:37:58