I have this code that graphs any number of datasets from txt files in one graph. It works very well but I am unable to figure out how to show the all file names in the Matplotlib graph legend. I can get the last file that was graphed to show in the legend, but that's all I can get. So how can I get every filename to show in the legend? You could test using the baseline files here at Github https://github.com/thomasawolff/verification_text_data
def graphWriterIRI():
figsize = plt.figure(figsize=(16,10))
# Set up the plots
plt.subplot(2, 1, 1)
plt.grid(True)
plt.ylabel('IRI value', fontsize=12)
#pylab.ylim([0,150])
plt.title('Right IRI data per mile for verification runs')
plt.tick_params(axis='both', which='major', labelsize=8)
plt.hold(True)
plt.subplot(2, 1, 2)
plt.grid(True)
plt.ylabel('IRI value', fontsize=12)
#pylab.ylim([0,150])
plt.title('Left IRI data per mile for verification runs:')
plt.tick_params(axis='both', which='major', labelsize=8)
plt.hold(True)
# Iterate over the files in the current directory
for filename in os.listdir(os.getcwd()):
# Initialize a new set of lists for each file
startList = []
endList = []
iriRList = []
iriLList = []
# Load the file
if filename.endswith('.TXT'):
with open(filename, 'rU') as file:
for row in csv.DictReader(file):
try:
startList.append(float(row['Start-Mi']))
endList.append(float(row[' End-Mi']))
except:
startList.append(float(row['Start-MP']))
endList.append(float(row[' End-MP']))
try:
iriRList.append(float(row[' IRI R e']))
iriLList.append(float(row['IRI LWP ']))
except:
iriRList.append(float(row[' IRI RWP']))
iriLList.append(float(row['IRI LWP ']))
# Add new data to the plots
try:
plt.subplot(2, 1, 1)
plt.plot(startList,iriRList)
plt.legend([filename]) # shows the last filename in the legend
plt.subplot(2, 1, 2)
plt.plot(startList,iriLList)
plt.legend([filename])
except ValueError:pass
#return iriRList,iriLList
plt.show()
plt.close('all')
graphWriterIRI()