Home > Software engineering >  How to generate matplotlib figures inside a for loop
How to generate matplotlib figures inside a for loop

Time:11-19

Hello I have a piece of code which reads an excel data file, does some stuff to it and then plots a figure. Now i want to be able to plot many excel data files at the same time and each should be plotted to its own figure.

example:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import MultiCursor
import matplotlib.pylab as pl

Files_to_read = np.array([r"C:\file1",r"C:\file2"])
for ii in range(len(Files_to_read)):
   df=pd.read_excel(Files_to_read[ii])
#do a lot of stuff to "df"
   fig, ((ax1,ax2),(ax3,ax4)) = plt.subplots(2,2,sharex=True)
   fig.suptitle('some name')
   p1 = ax1.plot(df["some vector"], df["some vector"])
   p2 = ax2.plot(df["some vector"], df["some vector"])
   p3 = ax3.plot(df["some vector"], df["some vector"])
   p4 = ax4.plot(df["some vector"], df["some vector"])
   multi = MultiCursor(fig.canvas, (ax1, ax2, ax3, ax4), color='r', lw=1)
   plt.show()

Doing it like this generates 1 figure with the data of the first file and then overwrites the same figure with the data of the second file, how can I change it to generate a new figure on each pass through the for loop?

CodePudding user response:

Move your call to plt.show() so that it occurs after the for loop has been complete. All created figures should be visualized at once.

  • Related