面向对象的pyplot

时间:2016-05-13 13:37:28

标签: python matplotlib

我需要处理pyplot对象,如图形和轴。以下是我想要的简化示例:

In [1]: import matplotlib.pyplot as mp

In [2]: fig = mp.figure()             # create a figure

In [3]: mp.show()                     # and immediately show it. And close.

In [4]: ax = fig.add_subplot(111)     # Then I create a plot on that figure

In [5]: ax.plot([1, 2, 3]) 
Out[5]: [<matplotlib.lines.Line2D at 0x104e29a50>]

In [6]: mp.get_fignums()              # But I already released the figure, so it doesn't appear in the list of available figures
Out[6]: []

In [7]: fig.axes[0].lines[0].get_data()   # The data is there, on the plot
Out[7]: (array([ 0.,  1.,  2.]), array([1, 2, 3]))

In [8]: mp.show()                     # But mp.show() shows nothing.

fig.show()也不起作用。释放后如何显示图形?

UPD:有一个类似的问题:Matplotlib: re-open a closed figure?,但没有答案。

3 个答案:

答案 0 :(得分:0)

试试这个:

import matplotlib.pyplot as mp

fig = mp.figure()

plt.show() # empty figure appears, close it

fig = plt.gcf() # get current figure, this is the key piece.

ax = fig.add_subplot(111) # added axes object

ax.plot([1,2,3])

plt.show()

当我这样做时,我能够绘制出用对角线绘制的情节。

答案 1 :(得分:0)

Which is the recommended way to plot: matplotlib or pylab?问题与此问题相关。

pyplot界面是一个便利模块,用于跟踪a)开放数字和b)当前数字&#39;和&#39;当前轴&#39;。它下面是使用OO界面。

要让一个开放的数字能够在repl中输入新命令,您需要进入交互式&#39;将python repl循环与GUI事件循环集成的模式。

从您的问题来看,您似乎正在使用IPython,因此请使用%matplotlib魔术:

16:31 $ ipython
Python 3.5.1 |Continuum Analytics, Inc.| (default, Dec  7 2015, 11:16:01) 
Type "copyright", "credits" or "license" for more information.

IPython 4.2.0 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.

In [1]: %matplotlib
Using matplotlib backend: Qt4Agg

In [2]: import matplotlib.pyplot as plt

In [3]: fig, ax = plt.subplots()  # prompt returns immediatly leaving open figure

In [4]: ln, = ax.plot(range(15), label='test')  # draws line and updates figure

In [5]: ln.set_linewidth(5)  # changes lw and updates screen

In [6]: 

答案 2 :(得分:-1)

我找到了!让我们创建一个mp.Figure()

import matplotlib.pyplot as mp
fig = mp.Figure()

现在它没有连接到pyplot,所以我们无法显示它。它等同于关闭数字时发生的情况。您无法显示未连接到pyplot的数字的事实已有详细记录。试试吧

In []: fig.show?
Docstring:
If using a GUI backend with pyplot, display the figure window.
For non-GUI backends, this does nothing.

(我缩小了帮助信息的内容。) 但有可能欺骗pyplot。让我们创建一个数字:

temp_fig = mp.figure()

从temp_fig窃取图形管理器并将其分配给我们的图:

m = mp.get_current_fig_manager()
fig.canvas.manager = m

现在我们可以展示它:

mp.show() # Shows the fig figure.

当然,删除temp_fig是一个好习惯:

del temp_fig