问题描述
我正在使用Jupyter Notebook绘制饼图图形.
I am using Jupyter Notebook for plotting piechart figures.
在我的代码的第一个单元格中,我有一个魔术命令%matplotlib inline
,在执行了此魔术命令之后,我运行了代码,一切正常,并且图形呈现.
In first cell with my code I have a magic command %matplotlib inline
and after this magic command I run my code, everything works fine and my figure renders.
但是在第二个单元格中,当我设置%matplotlib notebook
进行交互式绘图时,运行第二个单元格后,我的图形将无法渲染.
But in second cell when I set %matplotlib notebook
for interactive plotting my figure won't render after running this second cell.
我需要重新启动内核并再次使用%matplotlib notebook
运行单元,并且在此之前无法运行%matplotlib inline
命令.
I need to restart kernel and run cell with %matplotlib notebook
again and cannot run %matplotlib inline
command before that.
这是我的第一个单元格和%matplotlib inline
的代码,可以很好地呈现:
Here is my code for first cell with %matplotlib inline
, which renders fine:
import matplotlib.pyplot as plt
%matplotlib inline
labels = "No", "Yes"
sizes = [100, 50]
fig, ax = plt.subplots(figsize=(6, 6))
_, texts, autotexts = ax.pie(sizes, explode=explode, labels=labels, colors=colors, autopct='%1.1f%%',
shadow=False, startangle=90)
ax.axis('equal')
之后,我用相同的代码创建了第二个单元格,只是将%matplotlib inline
更改为%matplotlib notebook
.运行此单元格后,该图将无法渲染,我需要重新启动内核并再次运行此单元格.
After that I have second cell with same code, just %matplotlib inline
is changed to %matplotlib notebook
. Figure won't render after I run this cell and I need to restart kernel and run this cell again.
为什么?
推荐答案
您的命令顺序错误.在jupyter中导入pyplot之前,应先设置一个后端.换句话说,更改后端后,需要再次导入pyplot.
You just have the wrong order of your commands. A backend should be set before importing pyplot in jupyter. Or in other words, after changing the backend, pyplot needs to be imported again.
因此,在导入pyplot之前,请先调用%matplotlib ...
.
Therefore call %matplotlib ...
prior to importing pyplot.
在第一个单元格中:
%matplotlib inline
import matplotlib.pyplot as plt
plt.plot([1,1.6,3])
在第二个单元格中:
%matplotlib notebook
#calling it a second time may prevent some graphics errors
%matplotlib notebook
import matplotlib.pyplot as plt
plt.plot([1,1.6,3])
这篇关于在Jupyter Notebook中内联%matplotlib后无法使用%matplotlib笔记本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!