python matplotlib Agg与交互式绘图和紧凑布局

9 投票
2 回答
20386 浏览
提问于 2025-04-17 19:21

如果我使用这个后端,我就无法通过show()保持图像窗口打开(无论block=True是否设置)——它们几乎会立刻关闭。如果我不使用,我就会收到一个警告:

/Library/Python/2.7/site-packages/matplotlib-1.2.0-py2.7-macosx-10.8-intel.egg/matplotlib/tight_layout.py:225: UserWarning: tight_layout : falling back to Agg renderer warnings.warn("tight_layout : falling back to Agg renderer")

示例代码:

import matplotlib as mpl
mpl.use('Agg')      # With this line = figure disappears; without this line = warning
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab
import numpy as np

fig = plt.figure()
ax = fig.add_subplot(111)
mu, sigma = 0, 0.5
x = np.linspace(-3, 3, 100)
plt.plot(x, mlab.normpdf(x, mu, sigma))
fig.tight_layout()
plt.show()

我应该使用其他的后端或方法吗?

2 个回答

6

Agg 是一种 非交互式的后端,这意味着它不会在屏幕上显示图形,只会把图形保存到文件里。你现在用的是什么后端呢?如果你是用的OSX系统,可以试试'macosx',或者使用一个可以和Agg一起工作的交互式后端,比如QT4Agg或者WXAgg。

8

在这里,@FilipeCorreia 在评论中给出的解决办法是:去掉 mpl.use('Agg') 这一行,然后用 fig.set_tight_layout(True) 来代替 fig.tight_layout()

撰写回答