问题描述
因此,我有一个函数generategraph(file),该函数可根据参数中的数据正确创建条形图,然后将其保存.这是保存它的部分.
So I have a function generategraph(file) which correctly creates a bar graph based on the data in the parameter and then saves it. Here is the part that saves it.
plt.show()
savefile = file.split('.txt')[0] + '.png'
plt.savefig(savefile)
然后在主要方面,我将遍历一组文件,并在每个文件上调用generategraph.
then in main, I will go through a set of files and call generategraph on each one.
for fil in files:
generategraph(fil)
plt.show()为我提供了正确的图形(每次都不同的图形),但是当我转到保存的图形时,它们都是同一图形(因此len(文件)个已保存图形的数量,但每个都是第一个文件的图形(如果有意义).我只是感到困惑,因为plt.show()正在做我希望plt.savefig做的事情.
plt.show() gives me the correct graphs (different graphs each time), but when I go to the saved figures they are all of the same graph (so len(files) number of saved figures but each one is the graph of the first file if that makes sense). I am just confused because plt.show() is doing what I want plt.savefig to do.
推荐答案
您正在使用状态机(pyplot)界面.别.
You're using the state-machine (pyplot) interface. Don't.
显式创建人物:
fig1, ax1 = pyplot.subplots()
直接对他们采取行动:
lines, = ax1.plot(data1, data2, ...)
然后分别保存并关闭它们:
Then save and close them individually:
fig1.savefig(filename, dpi=300)
pyplot.close(fig1)
这篇关于Matplotlib savefig()在多个图形上保持保存同一图形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!