有没有更好的方法来重复使用Matplotlib?

时间:2015-02-07 02:18:45

标签: python 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()向我表明他们可能是一个更好的方法。我想做的事情就像是

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

但这似乎不起作用/例如第二次调用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描述讨论了阻塞和解除阻塞模式以及交互式和非交互式模式:

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的上下文中是相同的。

换句话说,有没有办法选择在代码中的不同点创建哪些图表来显示/叠加?

1 个答案:

答案 0 :(得分:0)

然而,尴尬,似乎是重复使用&#34;我的问题中描述的图是按照我原来的建议做的,并把它放在一个函数中。

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

然后如果你想重新使用该剧情,只需再次调用该函数:

some_plot()