2016-09-17 65 views
0

我正在通過ipython筆記本教程,它說要在單元中運行這個教程。 進口numpy的爲NP 進口數學 進口matplotlib.pyplot如PLT在ipython筆記本上顯示matplotlib時出錯

x = np.linspace(0, 2*math.pi) 
plt.plot(x, np.sin(x), label=r'$\sin(x)$') 
plt.plot(x, np.cos(x), 'ro', label=r'$\cos(x)$') 
plt.title(r'Two plots in a graph') 
plt.legend() 

,我應該得到一個實際的圖形。 Isntead我得到

<matplotlib.legend.Legend at 0x1124a2fd0> 

我應該怎麼做呢?

+1

'plt.show()應在該腳本的末尾加上'。 – Abdou

回答

3

嘗試前面添加此語句在你的筆記本電腦,這表明對matplotlib何處渲染的情節(即嵌入在筆記本中的HTML元素):

%matplotlib inline

背後的故事很簡單在jupyter和ipython筆記本變得流行之前,matplotlib已經足夠大了。那時創建劇情的標準方式就是寫一個腳本,運行它,然後獲得一個圖像文件作爲結果。目前,在筆記本中可以容易地直接看到相同的圖像,但需要以上述補充「重新佈線」聲明爲代價。

爲了在筆記本中顯示任何圖,您可以使用plot語句作爲該塊代碼的最後一行(即繪圖是返回的值,它會自動由jupyter呈現),或使用plt.show (),如Abdou在評論中所述。

同時,要小心,你有2個地塊在你的代碼:

# Put these 2 in two separate notebook blocks to get 2 separate plots. 
# As-is the first one will never get displayed 
plt.plot(x, np.sin(x), label=r'$\sin(x)$') 
plt.plot(x, np.cos(x), 'ro', label=r'$\cos(x)$') 

如果你想擁有的所有情節呈現爲一個單一的形象(這很快得到毛毛與matplotlib恕我直言),看看subplot documentation

爲了使結果更漂亮,包括;在情節的結尾,以避免醜陋 <matplotlib.legend.Legend at 0x1124a2fd0>

相關問題