Python 保存多个绘图

Python 保存多个绘图,python,matplotlib,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 i

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

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

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

保存绘图是正确的(只需将该代码放在
f.close()
之前,并确保使用
pl.savefig
而不是
plt.savefig
,因为您将
pyplot
作为
pl
导入)。您只需为每个输出绘图指定不同的文件名

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

fileName = "C:\documents\Plot-%04d.png" % ifile
另一个选项是根据输入的文件名生成唯一的输出文件名。您可以尝试以下方法:

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

这将采用输入路径,并将任何路径分隔符替换为
。您可以将其用作输出文件名的一部分。

只需提供唯一的文件名即可。您可以使用计数器:

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
我所做的:

  • 使用python的

  • 使用将计数器添加到循环中

  • 使用计数器和模板为每个绘图生成新文件名


嗨,谢谢你的帮助。我试过这种方法,而且都很有效,但结果却是一片空白。我还使用了pl.show(),它们生成了正确的绘图,只是没有实际的保存位。有什么想法吗?@user1841859:我不知道。可能需要
pl.show()
才能保存它?我自己没有使用过
pylab
plt.show()不能放在plt.savefig之前。你必须先保存它,然后再显示它。我原以为这是有效的,但现在意识到它正在为每个文件绘制并保存一个新文件,但每个文件都包含来自所有以前绘制的数据,上面只有新数据?@user1849:啊,这是一个单例绘制。指向一个clear方法
pl.clf()
,您还需要调用每个循环。