在 Jupyter Notebook 中内联 %matplotlib 之后使用 %matplotlib notebook 不起作用 [英] Using %matplotlib notebook after %matplotlib inline in Jupyter Notebook doesn't work
问题描述
我正在使用 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 notebook 不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!