2016-09-17 67 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>

相关问题