首页 > 解决方案 > 如何根据位于一个目录中的不同文件绘制不同的子图?

问题描述

我有一个包含 10 个不同 txt 文件的目录。每个 txt 文件包含一个 x 行和一个 y 行,文件的结构始终相同,但值彼此不同。我想绘制多个子图(总共 10 个,只有一个数字!),每个子图应该代表一个文件。换句话说,最后我想有十个不同的图,它们与 txt-files 一致。我的第一种方法如下:

%matplotlib inline
import glob
import pandas as pd
import matplotlib.pyplot as plt

data_path = 'C:\\Users\\MyPath'

fig, ax = plt.subplots(nrows=5, ncols=2, figsize=(8, 6))
fig.tight_layout()

files = glob.glob(data_path+'/*.txt')

for file in files:
    df = pd.read_csv(file)
    for row in range(5):
        for col in range(2):
            ax[row][col].plot(df['time'], df['signal'], c='green')

我的代码中的问题是所有文件都绘制在每个子图中,请参见示例: 示例子图 它在绘制它们之前循环遍历整个文件,但它应该在每个新文件处停止......我该如何解决这个问题,以便只有一个特定的文件在每个子图中“代表”?我将不胜感激任何建议。请记住,我不是专业人士。感谢您提前提供的帮助。

标签: pythonpandasmatplotlibsubplot

解决方案


ax是 Axes 的 numpy ndarray - 将其展平并使用文件对其进行迭代。

...
for axn,file in zip(ax.flatten(),files):
    df = pd.read_csv(file)
    axn.plot(df['time'], df['signal'], c='green')

或者:

...
for axn,file in zip(ax.flatten(),files):
    df = pd.read_csv(file)
    df.plot(x='time', y='signal', ax=axn, c='green')

https://matplotlib.org/3.2.1/api/_as_gen/matplotlib.pyplot.subplots.html


推荐阅读