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

Matplotlib循环读文件绘图 如何实现两个独立图表并排展示

问题说明
  • 需求:遍历读取两个后缀为.en的数据文件,针对每个文件分别绘制第一列与第二列数据的对应关系图,两个图表需左右并排独立展示
  • 现存问题:运行原有代码后,两组数据的曲线被绘制在同一坐标系内重叠显示,未实现两个独立图表并排排布的效果

原有实现代码

def plot_en(filename):

with open("%s.en" %filename,"r") as g_in:
    t=[]
    for line in g_in:
        t.append([ float(x) for x in line.split()])
        column1 = [ x[0] for x in t]
        column2 = [ x[1] for x in t]
        plt.plot(column1,column2)        
plot_en("tempor1")
plot_en("tempor2")

测试文件示例

  • tempor1.en内容:
500  1.1
550  2.1
600  2.2
650  3.1
700  3.9
  • tempor2.en内容:
500  3.1
550  3.5
600  3.8
650  4.0
700  4.9

问题原因

原有代码存在两个核心问题:

  1. 未提前创建多子图布局,matplotlib默认每次调用plt.plot()都会在当前激活的同一个坐标轴上绘制,直接导致两条曲线重叠
  2. 代码缩进错误,列数据提取逻辑被写在了逐行读取文件的循环内部,会产生大量冗余计算,且函数定义下的逻辑块没有正确缩进,缺少matplotlib库导入语句也会直接导致运行报错

修改后可运行代码

import matplotlib.pyplot as plt

def plot_en(filename, ax, title):
    data = []
    # 读取文件数据
    with open(f"{filename}.en", "r") as f:
        for line in f:
            line = line.strip()
            if not line:
                continue
            data.append([float(x) for x in line.split()])
    # 读完所有行后再提取两列数据
    col1 = [row[0] for row in data]
    col2 = [row[1] for row in data]
    # 在指定的子图坐标轴上绘图
    ax.plot(col1, col2)
    ax.set_title(title)
    ax.set_xlabel("第一列数值")
    ax.set_ylabel("第二列数值")

# 创建1行2列的并排子图布局,设置画布大小
fig, (ax1, ax2) = plt.subplots(nrows=1, ncols=2, figsize=(10, 4))
# 分别在两个子图上绘制对应文件的数据
plot_en("tempor1", ax1, "tempor1.en数据")
plot_en("tempor2", ax2, "tempor2.en数据")
# 自动调整子图间距,避免标签重叠
plt.tight_layout()
# 展示图像
plt.show()

实现效果

运行代码后会生成一个包含两个独立坐标系的画布,两个折线图左右并排展示,分别对应两个.en文件的数据,不会出现曲线重叠的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 19:51:18