2015-02-07 78 views
0

下面的代碼塊(A)解決了我能夠重複使用圖的整體問題,但是我想知道是否有更好的方法(不涉及爲每個plt.plot創建函數,如下所示有沒有更好的方式來重複使用Matplotlib地塊?

碼塊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 

但這似乎並不工作/例如第二次調用plt.show()不會產生第一個圖。 (即使你解開first_plot(這在現實中,從代碼塊B,是實際的列表):

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

這不能用於生產的情節再次反正我可以看到這可能是因爲。 plt.show和plt.plot之間的關係,我並不完全理解,plt.plot似乎把這個情節放在一個que中,然後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(假)(塊)它似乎沒有影響,例如在代碼塊A和B的情況下輸出是相同的。

換句話說,有沒有辦法選擇創建哪些圖來顯示/疊加在代碼中的不同點?

+0

什麼是「不工作」是什麼意思?怎麼了?什麼是錯誤或回溯的全文?什麼是期望的輸出?你是否理解將調用結果賦給'plot()'給變量的後果? – MattDMo 2015-02-07 02:44:51

+0

我重新提出了這個問題,希望更清楚。 「它不起作用」意味着第一個plot不會與plt.show()的第二個調用一起顯示。所需輸出將與代碼塊A的輸出相同,但所需輸入(我的代碼)不需要爲每個plot()創建一個函數。不,我不明白將調用結果分配給變量的結果,並且純粹是爲了展示我希望生成的更乾淨的代碼。也許處理這個問題的另一種方法是改變plt.show渲染的方式和方式。 – 2015-02-07 15:29:38

回答

0

不過尷尬,似乎最好的方式來「重複使用」的情節,如我的問題所述,是按照我原來的建議,並將其放入函數中。

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

,然後如果你想重新使用的情節只是再次調用函數:

some_plot() 
相關問題