保存多个图

时间:2012-11-25 20:18:01

标签: python matplotlib

我有这个代码从文件夹中的所有文本文件生成多个图。它运行得很好,并显示了情节,但我不知道如何将它们全部保存。

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()

我以前用过

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

但我认为这只是将每个图表保存到一个文件中并覆盖最后一个。

2 个答案:

答案 0 :(得分:10)

您所要做的就是提供唯一的文件名。你可以使用一个计数器:

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

我做了什么:

答案 1 :(得分:0)

您正在做正确的事情来保存图表(只需将代码放在f.close()之前,并确保使用pl.savefig而不是plt.savefig,因为您导入{{1作为pyplot)。您只需为每个输出图提供不同的文件名。

执行此操作的一种方法是添加一个计数器变量,该变量对于您经历的每个文件都会递增,并将其添加到文件名中,例如,执行以下操作:

pl

另一种选择是根据输入的文件名创建唯一的输出文件名。你可以尝试类似的东西:

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

这将采用输入路径,并用fileName = "C:\documents\Plot-" + "_".join(os.path.split(os.path.join(subdir,file))) + ".png" 替换任何路径分隔符。您可以将其用作输出文件名的一部分。

相关问题