Eric Stralsund
Eric Stralsund

Reputation: 559

Plot multiple csv files with 1 plot function

I have 4 different csv files (extracted from 1 xlsm workbook). My plot function is a bit complex but works really perfect on 1 of these files each. If I try to plot all 4 files with a loop I get always an

ValueError: arrays must all be same length

Then the function is plotting the first element from the list. I want to plot the same plt.figure with subplots for each file from csv list. I think the script is trying to plot all different csv files on one plot (the csv files have the same structure but different amount of rows)

def plotMSN(data):  

    csv = data  
    #csv = "LL.csv" (this is working perfect)
    day = plotday
    ....

#this is not working
csvlist = ["LL.csv","UL.csv","UR.csv","LR.csv"]

for i in csvlist:
    plotMSN(i)
    time.sleep(5)

Upvotes: 1

Views: 246

Answers (1)

mauve
mauve

Reputation: 2763

They will plot all on the same plot if you don't set up subplots. There's more than one method to do this, but the one I typically use is the fig, axis_array

import matplotlib.pyplot as plt

def plotMSN(i):
    #whatever you're doing in here
    ax.plot() #plot it on its own axis, this will reference the one you're on in your loop


fig, axis_array = plt.subplots(len(csvlist), 1, subplot_kw = {'aspect':1}) #this will set up subplots that are arranged vertically
for i, ax in zip(csvlist, axis_array):
    plotMSN(i)

ETA:

OP apparently wanted to plot each file and use the function. To that end, OP would need to modify:

def plotMSN(i):
  #determine an appropriate name either in this function or in the loop that calls it 
  #plotting stuff here
  fig.savefig(new_filename)
  plt.close() # this prevents it from using the same instance over and over. 

Upvotes: 1

Related Questions