Python编程入门:使用Matplotlib时遭遇AttributeError问题求助
问题原因与解决方法
错误根源
- 你使用的
Agg是非交互式后端,它完全不支持plt.show()方法,调用该方法会直接触发AttributeError——因为Agg没有图形显示能力,仅用于生成图片文件。 - 就算换用支持显示的后端,
plt.show()执行后Matplotlib会自动关闭当前绘制的figure,后续调用plt.savefig()时,已经没有可保存的图形对象,同样会报错。
修正后的代码(适配Agg后端)
直接移除plt.show()即可,你要的是把图片输出到stdout,不需要显示窗口:
import sys import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import numpy as np xpoints = np.array([0, 6]) ypoints = np.array([0, 250]) plt.plot(xpoints, ypoints) # 删掉plt.show(),Agg后端不支持该操作,且会破坏后续的savefig plt.savefig(sys.stdout.buffer) sys.stdout.flush()
额外说明(如果需要同时显示和保存)
如果是在有GUI的本地环境运行,想同时显示图形并保存,可以换成交互式后端(比如TkAgg),并且先调用savefig再调用show:
import sys import matplotlib # 切换为交互式后端(需确保环境有对应GUI依赖) matplotlib.use('TkAgg') import matplotlib.pyplot as plt import numpy as np xpoints = np.array([0, 6]) ypoints = np.array([0, 250]) plt.plot(xpoints, ypoints) plt.savefig(sys.stdout.buffer) # 先保存图形 plt.show() # 再显示窗口,此时figure不会被提前关闭 sys.stdout.flush()
内容的提问来源于stack exchange,提问作者Keith Indeche
相关产品推荐
相关产品推荐

