有没有更好的方法来重用绘图 Matplotlib?

Is there a better way to re-use plots Matplotlib?

下面的代码块 (A) 解决了我能够重用图的总体问题,但我想知道是否有更好的方法(不涉及为每个图创建函数的方法 plt.plot,如下图

代码块A:

import maptplotlib.pyplot as plt

#create a function just to call the plt.plot
def first_plot(): plt.plot(x,y) 
first_plot()
# Now i can just show the first plot
plt.show()

def second_plot(): plt.plot(x,z)

first_plot() # instead of plt.plot(x,y)
second_plot() # instead of plt.plot(x,z)
# now i can show both plots
plt.show()

如果情节复杂:

plot.plot(lots of details)

他们有很多:

plots = [first,second,third,fourth,...]

我认为这将是有利的,因为它避免了代码重用。

然而,创建一个函数只是为了调用 plt.plot() 向我表明他们可能更好 way.what 我想做的是

first_plot = plt.plot(x,y)
first_plot()
#now i want to show just the first plot
plt.show() # first call

second_plot = plt.plot(x,z)
# now i want to show them together combined
first_plot() 
second_plot()
plt.show() # second call

但这似乎 work/e.g 第二次调用 plt.show() 不会产生第一个情节。 (即使你解包 first_plot(实际上,从代码块 B 中,它实际上是一个列表):

In [17]: first_plot
Out[17]: [<matplotlib.lines.Line2D at 0x7fd33ac8ff50>]

无论如何我都不能再用它来制作剧情了。这可能是因为plt.show和plt.plot之间的关系,我不太明白。 Plt.plot 似乎把情节放在一个问题中,然后 plt.show 弹出。然而, plt.shows description 谈到阻塞和解除阻塞模式以及交互和非交互模式:

show(*args, **kw)
    When running in ipython with its pylab mode, display all
    figures and return to the ipython prompt.

    In non-interactive mode, display all figures and block until
    the figures have been closed; in interactive mode it has no
    effect unless figures were created prior to a change from
    non-interactive to interactive mode (not recommended).  In
    that case it displays the figures but does not block.

    A single experimental keyword argument, *block*, may be
    set to True or False to override the blocking behavior
    described above.

我不明白。但是无论我如何调用 plt.show() vs plt.show(False)(阻塞?)它似乎都没有影响,例如在代码块 A 和 B 的上下文中输出是相同的.

所以换句话说,有没有办法 select 在代码的不同点创建哪些绘图到 show/overlay?

无论多么尴尬,似乎 "re-use" 我的问题中描述的绘图的最佳方法是按照我最初的建议将其放入函数中。

def some_plot(): return plot(x,y)

然后,如果您想重新使用绘图,只需再次调用该函数即可:

some_plot()