python - 在 Jupyter Notebook 中的 %matplotlib inline 之后使用 %matplotlib notebook 不起作用

标签 python matplotlib jupyter-notebook

我正在使用 Jupyter Notebook 绘制饼图。

第一个单元格中我的代码有一个魔术命令%matplotlib inline,在这个魔术命令之后我运行我的代码,一切正常并且我的图形渲染。

但是在 第二个单元格 中,当我设置 %matplotlib notebook 进行交互式绘图时,我的图形在运行第二个单元格后不会呈现。

我需要重新启动内核并再次使用 %matplotlib notebook 运行单元,并且在此之前无法运行 %matplotlib inline 命令。

这是我的 first cell 代码,带有 %matplotlib inline,渲染效果很好:

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。运行此单元后,图形不会呈现,我需要重新启动内核并再次运行此单元。

为什么?

最佳答案

你只是有错误的命令顺序。在 jupyter 中导入 pyplot 之前应该设置一个后端。或者换句话说,改变后端后,需要重新导入pyplot。

因此在导入 pyplot 之前调用 %matplotlib ...

在第一个单元格中:

%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])

关于python - 在 Jupyter Notebook 中的 %matplotlib inline 之后使用 %matplotlib notebook 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43545050/

相关文章:

python - 如何对在 __init__ 方法之外初始化的实例变量进行单元测试

python - 使用 XPath 查找最上面的以下元素

python - matplotlib 类型错误 : unsupported operand type(s) for -: 'datetime.date' and 'float'

python-3.x - Matplotlib:每个刻度都有不同的颜色

jupyter-notebook - 如何在等式Jupyter笔记本的文本中添加空格?

python - 如何更改Python中矩阵值的格式?

python查找文件中正则表达式匹配次数最多的部分

python - Django 在不使用 "request.path"的情况下获取 url 路径

python - 值错误 : 'vertices' must be a 2D list or array with shape Nx2

python - 如何在 jupyter-notebook 中逐行执行代码?