这将在GUI中显示图形:
import matplotlib.pyplot as plt
plt.plot([1, 2, 3], [1, 4, 9])
plt.show()
但我如何将图形保存到文件(例如foo.png)中?
这将在GUI中显示图形:
import matplotlib.pyplot as plt
plt.plot([1, 2, 3], [1, 4, 9])
plt.show()
但我如何将图形保存到文件(例如foo.png)中?
当前回答
刚刚在MatPlotLib文档中找到了解决此问题的链接:http://matplotlib.org/faq/howto_faq.html#generate-图像-无窗口外观
他们说,防止弹出图形的最简单方法是通过matplotib.use(<backend>)使用非交互式后端(例如Agg),例如:
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
plt.plot([1,2,3])
plt.savefig('myfig')
我个人还是更喜欢使用plt.close(图),因为这样你就可以选择隐藏某些数字(在循环期间),但仍然可以显示循环后数据处理的数字。它可能比选择非交互式后端要慢——如果有人测试了它,那会很有趣。
UPDATE:对于Spyder,通常不能以这种方式设置后端(因为Spyder通常会提前加载matplotlib,从而阻止您使用matplotlib.use())。
相反,请使用plt.switch_backend('Agg'),或在Spyder prefs中关闭“enable support”,然后自己运行matplotlib.use('Agg')命令。
从这两个提示中:一、二
其他回答
解决方案是:
pylab.savefig('foo.png')
由于服务器上没有gui,因此使用“agg”。使用gui和VSC在ubuntu 21.10上进行调试。在调试中,尝试显示绘图,然后保存到web UI的文件。
发现显示前需要保存,否则保存的绘图为空。我想这场演出会因为某种原因使剧情明朗化。执行以下操作:
plt.savefig(imagePath)
plt.show()
plt.close(fig)
而不是:
plt.show()
plt.savefig(imagePath)
plt.close(fig)
除上述内容外,我还为名称添加了__file__,以便图片和Python文件获得相同的名称。我还添加了一些参数以使它看起来更好:
# Saves a PNG file of the current graph to the folder and updates it every time
# (nameOfimage, dpi=(sizeOfimage),Keeps_Labels_From_Disappearing)
plt.savefig(__file__+".png",dpi=(250), bbox_inches='tight')
# Hard coded name: './test.png'
使用matplotlib.pyplot时,必须先保存绘图,然后使用以下两行关闭绘图:
fig.savefig('plot.png') # save the plot, place the path you want to save the figure in quotation
plt.close(fig) # close the figure window
您可以执行以下任一操作:
plt.show(hold=False)
plt.savefig('name.pdf')
记住在关闭GUI绘图之前让savefig完成。这样您可以提前看到图像。
或者,您可以使用plt.show()查看它然后关闭GUI并再次运行脚本,但这次将plt.show()替换为plt.savefig()。
或者,您可以使用
fig, ax = plt.figure(nrows=1, ncols=1)
plt.plot(...)
plt.show()
fig.savefig('out.pdf')