[英]Matplotlib savefig() over multiple graphs keeps saving the same graph
所以我有一个函数generategraph(file),它根据参数中的数据正确创建条形图,然后保存它。 这是保存它的部分。
plt.show()
savefile = file.split('.txt')[0] + '.png'
plt.savefig(savefile)
然后在main中,我将浏览一组文件并在每个文件上调用generategraph。
for fil in files:
generategraph(fil)
plt.show()给了我正确的图形(每次都有不同的图形),但是当我去保存的图形时它们都是相同的图形(所以len(文件)保存的数字的数量,但每一个是图形的第一个文件,如果这是有道理的)。 我只是感到困惑,因为plt.show()正在做我想要的plt.savefig。
您正在使用状态机(pyplot)接口。 别。
明确地创建您的数字:
fig1, ax1 = pyplot.subplots()
直接采取行动:
lines, = ax1.plot(data1, data2, ...)
然后单独保存并关闭它们:
fig1.savefig(filename, dpi=300)
pyplot.close(fig1)
您可能需要验证保存的图形名称是否各不相同。 (以下是伪代码,目前尚不清楚如何获取文件名。)
[edit]然后你可能应该在plt.savefig(savefile)
之后放置plt.show()
plt.savefig(savefile)
#initialize idx to 0 earlier, and don't re-initialize it.
idx += 1
savefile = file + str(idx) + '.png' # file might need to be replaced by a string
plt.savefig(savefile)
plt.show() # place after plt.savefig()
或者,您可以更改generategraph
的签名
def generategraph(file, idx):
savefile = file + str(idx) + '.png' # file might need to be replaced by a string
plt.savefig(savefile)
plt.show() # place after plt.savefig()
for idx, fil in enumerate(files):
generategraph(fil, idx)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.