这将在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)中?
当前回答
嗯,我确实建议使用包装器来渲染或控制绘图。示例可以是mpltex(https://github.com/liuyxpp/mpltex)或prettyplotlib(https://github.com/olgabot/prettyplotlib).
import mpltex
@mpltex.acs_decorator
def myplot():
plt.figure()
plt.plot(x,y,'b-',lable='xxx')
plt.tight_layout(pad=0.5)
plt.savefig('xxxx') # the figure format was controlled by the decorator, it can be either eps, or pdf or png....
plt.close()
我基本上经常使用这个装饰器在美国化学学会、美国物理学会、美国光学学会、Elsivier等各种期刊上发表学术论文。
示例如下图所示(https://github.com/MarkMa1990/gradientDescent):
其他回答
使用matplotlib.pyplot.savefig时,可以通过扩展名指定文件格式:
from matplotlib import pyplot as plt
plt.savefig('foo.png')
plt.savefig('foo.pdf')
这分别提供光栅化或矢量化输出。此外,图像周围有时存在不希望有的空白,可以通过以下方式删除:
plt.savefig('foo.png', bbox_inches='tight')
注意,如果显示绘图,plt.show()应跟随plt.savefig();否则,文件图像将为空。
如果像我一样使用Spyder IDE,则必须禁用交互模式:
plt.ioff()
(此命令在科学启动时自动启动)
如果要再次启用,请使用:
plt.ion()
刚刚在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')命令。
从这两个提示中:一、二
import matplotlib.pyplot as plt
plt.savefig("image.png")
在Jupyter Notebook中,您必须在一个单元格中删除plt.show()并添加plt.savefig()以及其他plt代码。图像仍将显示在笔记本中。
使用plot()和其他函数创建所需的内容后,可以使用如下子句在绘制到屏幕或文件之间进行选择:
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(4, 5)) # size in inches
# use plot(), etc. to create your plot.
# Pick one of the following lines to uncomment
# save_file = None
# save_file = os.path.join(your_directory, your_file_name)
if save_file:
plt.savefig(save_file)
plt.close(fig)
else:
plt.show()