matplotlib - 使用 %matplotlib 笔记本时,图形和 ipywidget 不能位于同一代码单元中

标签 matplotlib ipython jupyter-notebook ipywidgets

我想制作一个图形并使用 ipywidgets 交互地更改它。 当我使用%matplotlib笔记本时,小部件调用需要位于单独的代码单元中,这很奇怪。这是不起作用的代码

import matplotlib.pyplot as plt
from matplotlib.patches import Circle
%matplotlib notebook

fig = plt.figure(figsize=(6, 6))
ax1 = plt.subplot(111, aspect='equal')
ax1.set_xlim(-5,5)
ax1.set_ylim(-5,5)
circ = Circle((0,0), radius=1)
ax1.add_patch(circ)

def change_radius(r=1):
    circ.set_radius(r)

from ipywidgets import interact
interact(change_radius, r=(1.0, 5))

仅当最后两行位于单独的代码单元中时才有效,但随后小部件通过代码单元与图形分开。有谁知道如何让它在一个代码单元中使用 %matplotlib notebook 工作?

最佳答案

您应该在 change_radius() 中使用 display(fig) 显式调用该图窗:

import matplotlib.pyplot as plt
from matplotlib.patches import Circle
from IPython.display import display
%matplotlib notebook

fig = plt.figure(figsize=(6, 6))
ax1 = plt.subplot(111, aspect='equal')
ax1.set_xlim(-5,5)
ax1.set_ylim(-5,5)
circ = Circle((0,0), radius=1)
ax1.add_patch(circ)

def change_radius(r=1):
    circ.set_radius(r)
    display(fig)

from ipywidgets import interact
interact(change_radius, r=(1.0, 5))

关于matplotlib - 使用 %matplotlib 笔记本时,图形和 ipywidget 不能位于同一代码单元中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36058649/

相关文章:

python - 使用 QtDesigner 连接 Pyside 与 Matplotlib - 使用 pushButton 进行绘图

ipython - 在 IPython 笔记本中操作内联图形

python - 在图中移动图形位置 (matplotlib)

python - 如何在不重新运行脚本的情况下重置 matplotlib 动画

python - 如何启动 Python ipython shell,自动在其中运行一些命令,并保持打开状态?

Jupyter笔记本: enable vertical scrolling in code block

python - 你如何更新 Ipython 中的内联图像?

python - 如何使用iPython 7.x中使用的prompt_toolkit实现双引号、圆括号、方括号的自动关闭?

python - 如何在 Pycharm pro *中以标准布局*查看 Jupyter notebook?

python - 在 Jupyter 笔记本上安装 Linearmodels 包时出错