当然!你需要做的是绕过pyplot
当你制作图形时完全是状态机。
它更详细,因为你不能直接调用fig = plt.figure()
.
首先,让我解释一下如何plt.gca()
or plt.gcf()
作品。当使用pyplot
接口,matplotlib 存储所有已创建但未显示的图形管理器。图形管理器基本上是图形的 GUI 包装器。
plt._pylab_helpers.Gcf
是存储图窗管理器并跟踪当前处于活动状态的单例对象。plt.gcf()
返回活动数字_pylab_helpers.Gcf
. Each Figure
对象跟踪它自己的轴,所以plt.gca()
只是plt.gcf().gca()
.
通常,当您拨打电话时plt.figure()
, it:
- 创建返回的图形对象
- 创建一个
FigureManager
对于该数字使用适当的后端
- 图形管理器创建一个
FigureCanvas
、GUI 窗口(根据需要)和NavigationToolbar2
(缩放按钮等)
- 然后将图形管理器实例添加到
_pylab_helpers.Gcf
的数字列表。
这是我们想要绕过的最后一步。
这是一个使用非交互式后端的简单示例。请注意,因为我们不担心与绘图交互,所以我们可以跳过整个图形管理器,只创建一个Figure
and FigureCanvas
实例。 (从技术上讲,我们可以跳过FigureCanvas
,但是当我们想要将绘图保存到图像等时就需要它。)
import matplotlib.backends.backend_agg as backend
from matplotlib.figure import Figure
# The pylab figure manager will be bypassed in this instance. `plt.gca()`
# can't access the axes created here.
fig = Figure()
canvas = backend.FigureCanvas(fig)
ax = fig.add_subplot(111)
只是为了证明这一点gca
看不到这个轴:
import matplotlib.pyplot as plt
import matplotlib.backends.backend_agg as backend
from matplotlib.figure import Figure
# Independent figure/axes
fig = Figure()
canvas = backend.FigureCanvas(fig)
ax = fig.add_subplot(111)
ax.plot(range(10))
# gca() is completely unaware of this axes and will create a new one instead:
ax2 = plt.gca()
print 'Same axes?:', id(ax) == id(ax2)
# And `plt.show()` would show the blank axes of `ax2`
有了交互式支持,事情就变得更加复杂了。你不能打电话plt.show()
,所以你需要自己启动gui的主循环。您可以“从头开始”完成这一切(请参阅任何“嵌入 matplotlib”示例),但是FigureManager
抽象出支持的特定部分:
作为使用 TkAgg 后端的示例:
import matplotlib.backends.backend_tkagg as backend
from matplotlib.figure import Figure
fig = Figure()
ax = fig.add_subplot(111)
manager = backend.new_figure_manager_given_figure(1, fig)
manager.show()
backend.show.mainloop()
要使用其他后端之一,只需更改后端导入即可。例如,对于 Qt4:
import matplotlib.backends.backend_qt4agg as backend
from matplotlib.figure import Figure
fig = Figure()
ax = fig.add_subplot(111)
manager = backend.new_figure_manager_given_figure(1, fig)
manager.show()
backend.show.mainloop()
这实际上甚至适用于nbagg
IPython 笔记本中使用的后端。只需将后端导入更改为import matplotlib.backends.backend_nbagg as backend