首页 文章

在ipython笔记本中显示matplotlib时出错

提问于
浏览
0

我正在阅读一个ipython笔记本教程,它说要在一个单元格中运行它 . import numpy as np import math import matplotlib.pyplot as plt

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 回答

  • 3

    尝试在笔记本中添加此语句,这表示matplotlib在哪里渲染绘图(即作为嵌入在笔记本中的html元素):

    %matplotlib inline

    背后的故事就是matplotlib已经足够老了,因为在jupyter和ipython笔记本开始流行之前就存在了 . 那时候创建绘图的标准方法是编写脚本,运行它,并获得一个图像文件作为结果 . 目前,可以在笔记本中容易且直接地看到相同的图像,代价是上面的补充“重新布线”声明 .

    为了显示笔记本中的任何绘图,您可以将 plot 语句作为该块代码的最后一行(即该绘图是返回值,由jupyter自动呈现),或者使用如所描述的plt.show()阿卜杜在评论中说 .

    另外,请注意您的代码中有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 imho快速变得毛茸茸),请查看subplot documentation

    为了使结果更漂亮,在情节的末尾包括一个 ; 以避免丑陋的 <matplotlib.legend.Legend at 0x1124a2fd0>

相关问题