2013-07-09 16 views
5

假設我有一些數據,我想通過將它傳遞給一個自定義繪圖函數(myplot())來創建這個數據的圖。我在myplot()中使用了matplotlib的模塊。如何讓一個函數在Python中返回一個圖形(使用matplotlib)?

我希望myplot()將句柄返回給某個圖形,而不是在我調用此函數時繪圖顯示該圖形。以下是iPython的示例代碼和輸出。

enter image description here

我有這方面的兩個問題:

  1. 爲什麼我還是看到了情節,即使我分配 myplot()到F的輸出?
  2. 當我將myplot()的輸出分配給一個變量時,我需要什麼來抑制這個圖?
+0

這只是一個iPython Notebook功能,對吧?因爲我在IDLE中傳遞數字時沒有看到情節。 –

回答

5

啓動IPython中與

ipython notebook

而不是

ipython notebook --pylab=inline

enter image description here

+1

我認爲你不必以非內聯模式啓動整個筆記本會話。您可以使用以下命令來控制內聯後端行爲。 '%config InlineBackend.close_figures = False' 這將防止您的情節立即關閉(因此顯示在瀏覽器內)。 – ala

1

如果你不想開始在非直列作案的整個筆記本你可以使用下面的代碼:

%config InlineBackend.close_figures = False 

def myplot(t,x): 
    fig = figure() 
    x = plot(t,x) 
    fig.savefig('plot.png') # This is just to show the figure is still generated 
    return fig 

t = arange(0,6,0.01) 
x = sin(t) 

f = myplot(t,x) 
+0

這沒有奏效。我仍然得到與我的問題中所示相同的輸出。 – siva82kb

相關問題