9

i have this code to produce multiple plots from all the text files in a folder. It runs perfectly fine and shows the plots but i cant work out how to then 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 have previously used

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

but i think this just saves each graph into one file and overwrites the last one.

EnricoGiampieri
  • 5,947
  • 1
  • 27
  • 26
user1841859
  • 145
  • 1
  • 2
  • 5

2 Answers2

11

All you have to do is provide unique filenames. You could 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 did:

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • hi, thanks for your help. ive tried this method and its all working, but the plots are coming out blank. I used the pl.show() aswell, and they produced the right plot, just not the actual saving bit. any ideas? – user1841859 Nov 25 '12 at 21:18
  • @user1841859: I have no idea. Perhaps `pl.show()` is required before you can save it? I have not used `pylab` myself. – Martijn Pieters Nov 25 '12 at 21:19
  • plt.show() cannot come before plt.savefig You must save it first before showing it. – arynaq Nov 25 '12 at 21:22
  • I thought this was working, but now realised for each file it is plotting and saving a new file, but each one contains data from all the previous plots with just the new data on top? – user1841859 Nov 26 '12 at 12:48
  • @user1841859: Ah, it's a singleton plot. The [API](http://matplotlib.org/api/pyplot_api.html) points to a clear method `pl.clf()`, you'll need to call that each loop too. – Martijn Pieters Nov 26 '12 at 12:54
  • that works great now thanks! its amazing how one little line can cause so much trouble! – user1841859 Nov 26 '12 at 12:58
  • is there a way to specify the figure you want to save? – Lakshmi Narayanan Jan 21 '17 at 06:53
0

You’re doing the right thing to save the plot (just put that code before f.close(), and make sure to use pl.savefig rather than plt.savefig, since you import pyplot as pl). You just have to give each output plot a different filename.

One way to do this is to add a counter variable that gets incremented for each file you go through, and add that to the filename, for instance, doing something like this:

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

Another option is to make a unique output filename based on the filename of the input. You could try something like:

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

That will take the input path, and replace any path separators with _. You can use this as a part of your output filename.

illya
  • 765
  • 5
  • 8