Reputation: 61
I’ve got a directory with 10 different txt-files. Every txt-file contains one x-row and one y-row, the structure of the files is always the same, but the values are different from each other. I want to plot multiple subplots (10 in total, only one figure!), and each subplot should represent exactly one file. In other words, at the end I would like to have ten different plots, which are in accordance with the txt-files. My first approach is as follows:
%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')
The problem in my code is that all files are plotted in every subplot, see example:
It loops over the entire files before plotting them, but it should stop at every new file… How can I solve the problem, so that only one specific file is “represented” in each subplot?
I would be grateful for any advice. Please keep in mind that I'm not a professional. Thanks for the help already in advance.
Upvotes: 3
Views: 766
Reputation: 23753
ax
is a numpy ndarray of Axes - flatten it and iterate over it with the files.
...
for axn,file in zip(ax.flatten(),files):
df = pd.read_csv(file)
axn.plot(df['time'], df['signal'], c='green')
Or:
...
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
Upvotes: 1