这将在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)中?
当前回答
解决方案:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
matplotlib.style.use('ggplot')
ts = pd.Series(np.random.randn(1000), index=pd.date_range('1/1/2000', periods=1000))
ts = ts.cumsum()
plt.figure()
ts.plot()
plt.savefig("foo.png", bbox_inches='tight')
如果您想显示图像并保存图像,请使用:
%matplotlib inline
之后导入matplotlib
其他回答
根据问题Matplotlib(pyplot)savefig输出空白图像。
有一点需要注意:如果您使用plt.show,并且它应该在plt.savefig之后,否则您将给出一个空白图像。
详细示例:
import numpy as np
import matplotlib.pyplot as plt
def draw_result(lst_iter, lst_loss, lst_acc, title):
plt.plot(lst_iter, lst_loss, '-b', label='loss')
plt.plot(lst_iter, lst_acc, '-r', label='accuracy')
plt.xlabel("n iteration")
plt.legend(loc='upper left')
plt.title(title)
plt.savefig(title+".png") # should before plt.show method
plt.show()
def test_draw():
lst_iter = range(100)
lst_loss = [0.01 * i + 0.01 * i ** 2 for i in xrange(100)]
# lst_loss = np.random.randn(1, 100).reshape((100, ))
lst_acc = [0.01 * i - 0.01 * i ** 2 for i in xrange(100)]
# lst_acc = np.random.randn(1, 100).reshape((100, ))
draw_result(lst_iter, lst_loss, lst_acc, "sgd_method")
if __name__ == '__main__':
test_draw()
解决方案:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
matplotlib.style.use('ggplot')
ts = pd.Series(np.random.randn(1000), index=pd.date_range('1/1/2000', periods=1000))
ts = ts.cumsum()
plt.figure()
ts.plot()
plt.savefig("foo.png", bbox_inches='tight')
如果您想显示图像并保存图像,请使用:
%matplotlib inline
之后导入matplotlib
嗯,我确实建议使用包装器来渲染或控制绘图。示例可以是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时,必须先保存绘图,然后使用以下两行关闭绘图:
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
刚刚在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')命令。
从这两个提示中:一、二