简体   繁体   English

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

[英]Error displaying a matplotlib in ipython notebook

I'm going though a ipython notebook tutorial and it says to run this in a cell. 我正在看一个ipython笔记本教程,它说要在一个单元格中运行它。 import numpy as np import math import matplotlib.pyplot as plt 导入numpy作为np导入数学导入matplotlib.pyplot作为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() 

and I should get an actual graph. 我应该得到一个实际的图。 Isntead I get Isntead我明白了

<matplotlib.legend.Legend at 0x1124a2fd0>

What should I do instead? 我该怎么办呢?

Try to add this statement earlier in your notebook, which indicates to matplotlib where to render the plot (ie as an html element embedded in the notebook): 尝试在笔记本中更早地添加以下语句,该语句向matplotlib指示在何处呈现绘图(即,作为笔记本中嵌入的html元素):

%matplotlib inline

The story behind that is simply that matplotlib is old enough to be existing since before jupyter and ipython notebooks became popular. 其背后的故事仅仅是因为matplotlib足够老,足以在jupyter和ipython笔记本普及之前就存在。 Back then the standard way of creating a plot was to write a script, run it, and obtain an image file as result. 那时,创建绘图的标准方法是编写脚本,运行脚本并获取图像文件作为结果。 Currently the same image can be easily and directly visible in the notebook, at the cost of the supplementary "rewiring" statement above. 当前,相同的图像可以在笔记本电脑中轻松直接看到,但要付出上述补充“重新编写”声明的代价。

In order to display any plot in the notebook, you can have the plot statement as last line of that block code (ie the plot is then the returned value, which get rendered by jupyter automatically), or use plt.show() as described by Abdou in the comment. 为了在笔记本中显示任何绘图,您可以将plot语句作为该块代码的最后一行(即,绘图就是返回的值,由jupyter自动呈现),或使用plt.show()进行描述。由Abdou发表评论。

Also, watch out that you have 2 plots in your code: 另外,请注意您的代码中有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)$') 

If you want to have all plots rendered as one single image (which quickly gets hairy with matplotlib imho), have a look at subplot documentation 如果您想将所有图绘制为一个图像(使用matplotlib imho会很快变得麻烦),请查看子图文档

To make the result prettier, include a ; 为了使结果更美观,请添加; at the end of the plot to avoid the ugly <matplotlib.legend.Legend at 0x1124a2fd0> 在图的末尾避免难看的<matplotlib.legend.Legend at 0x1124a2fd0>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM