【问题标题】:How to use ipywidget's `interact` with matplotlib's `plt.subplots()`?如何将 ipywidgets `interact` 与 matplotlib `plt.subplots()` 一起使用?
【发布时间】:2020-11-19 16:32:11
【问题描述】:

ipywidgets 文档中提供的玩具示例如下:

%matplotlib inline
from ipywidgets import interactive
import matplotlib.pyplot as plt
import numpy as np

def f(m, b):
    plt.figure(2)
    x = np.linspace(-10, 10, num=1000)
    plt.plot(x, m * x + b)
    plt.ylim(-5, 5)
    plt.show()

interactive_plot = interactive(f, m=(-2.0, 2.0), b=(-3, 3, 0.5))
output = interactive_plot.children[-1]
output.layout.height = '350px'
interactive_plot

我尝试了以下方法,但不起作用:

%matplotlib inline
from ipywidgets import interactive
import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots()
ax.set_ylim(-5, 5)

def f(m, b):
    global ax
    ax.cla()
    x = np.linspace(-10, 10, num=100)
    ax.plot(x, m * x + b)
    # fig.canvas.draw() ?
    

interactive_plot = interactive(f, m=(-2.0, 2.0), b=(-3, 3, 0.5))
output = interactive_plot.children[-1]
output.layout.height = '350px'
interactive_plot

在这种情况下使用Axes 对象时会出现什么问题?

【问题讨论】:

    标签: python matplotlib jupyter-notebook ipywidgets


    【解决方案1】:

    两种解决方案:

    您可以在函数内移动图形创建,即

    %matplotlib inline
    from ipywidgets import interactive
    import matplotlib.pyplot as plt
    import numpy as np
    
    def f(m, b):
        # move here
        fig, ax = plt.subplots()
        ax.set_ylim(-5, 5)
        ...
        
    ...
    

    或者使用matplotlib的笔记本模式代替内联模式:%matplotlib notebook

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-08-06
      • 2017-09-14
      • 1970-01-01
      • 2016-06-20
      • 2011-09-23
      • 2017-02-28
      • 2022-06-11
      相关资源
      最近更新 更多