先说一下错误环境,我是用xshell远程登录linux系统,在python下用matplotlib进行生成png图片功能,结果报以上错误
查了相关博客说要添加matplotlib.use('Agg')这句话,结果发现没用,后来继续查看到了解释方案The main problem is that (on your system) matplotlib chooses an x-using backend by default. I just had the same problem on one of my servers. The solution for me was to add the following code in a place that gets read before any other pylab/matplotlib/pyplot import(原链接:https://stackoverflow.com/questions/2801882/generating-a-png-with-matplotlib-when-display-is-undefined)。意思就是matplotlib设置agg要放在任何导入的其它相关包前面
更改后我的代码:
import matplotlib
matplotlib.use('Agg')
import numpy as np
import matplotlib.pyplot as plt
x = np.random.randn(60)
y = np.random.randn(60)
plt.scatter(x,y,s=20)
out_png = 'out_file.png'
plt.savefig(out_png, dpi=150)