python - 如何根据位于一个目录中的不同文件绘制不同的子图?
问题描述
我有一个包含 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')
我的代码中的问题是所有文件都绘制在每个子图中,请参见示例: 它在绘制它们之前循环遍历整个文件,但它应该在每个新文件处停止......我该如何解决这个问题,以便只有一个特定的文件在每个子图中“代表”?我将不胜感激任何建议。请记住,我不是专业人士。感谢您提前提供的帮助。
解决方案
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
推荐阅读
- python - 从 csv 文件格式化表格
- postgresql - 如何有效地将 BigQuery 表迁移到本地 Postgres?
- spring - 添加 JoinColumn 注释时未在数据库上创建实体
- javascript - 如何将值从 jsx/redux/mongoDB 传递给 js 函数?
- c# - Unity C#如何改变函数中的bool
- reactjs - 更新状态 - 为什么在调用 setState 时创建新的状态副本?
- django - 如何从 djoser 包自定义登录 api?
- django - django 中是否有默认文件上传大小限制?
- c - C: 指向数组的指针!= 指向 &array[0] 的指针?
- google-cloud-firestore - 了解 Firebase Firestore 规则