Saving multiple charts

I have this code to create multiple graphs from all text files in a folder. It works fine and shows graphs, but I cannot decide how to save them all.

import re import numpy as np import matplotlib.pyplot as plt import pylab as pl import os rootdir='C:\documents\Neighbors for each search id' for subdir,dirs,files in os.walk(rootdir): for file in files: f=open(os.path.join(subdir,file),'r') print file data=np.loadtxt(f) #plot data pl.plot(data[:,1], data[:,2], 'gs') #Put in the errors pl.errorbar(data[:,1], data[:,2], data[:,3], data[:,4], fmt='ro') #Dashed lines showing pmRa=0 and pmDec=0 pl.axvline(0,linestyle='--', color='k') pl.axhline(0,linestyle='--', color='k') pl.show() f.close() 

I previously used

 fileName="C:\documents\FirstPlot.png" plt.savefig(fileName, format="png") 

but I think it just saves each graph in one file and overwrites the last one.

+7
source share
2 answers

All you have to do is provide unique file names. You can use a counter:

 fileNameTemplate = r'C:\documents\Plot{0:02d}.png' for subdir,dirs,files in os.walk(rootdir): for count, file in enumerate(files): # Generate a plot in `pl` pl.savefig(fileNameTemplate.format(count), format='png') pl.clf() # Clear the figure for the next loop 

What I've done:

+9
source

You are doing the right thing to save the plot (just put this code before f.close() and make sure to use pl.savefig and not plt.savefig , since you are importing pyplot as pl ). You just need to give each output chart a different file name.

One way to do this is to add a counter variable that will increment for each file you go through, and add this to the file name, for example, something like this:

 fileName = "C:\documents\Plot-%04d.png" % ifile 

Another option is to create a unique output file name based on the input file name. You can try something like:

 fileName = "C:\documents\Plot-" + "_".join(os.path.split(os.path.join(subdir,file))) + ".png" 

This will take the input path and replace any path separators with _ . You can use this as part of your output file name.

0
source

All Articles