【问题标题】:Matplotlib figure is not updating with ipywidgets sliderMatplotlib 图未使用 ipywidgets 滑块更新
【发布时间】:2021-05-06 07:21:51
【问题描述】:

我有以下代码来生成一个简单的图表。

%matplotlib notebook
from ipywidgets import *
import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 2 * np.pi)
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
line, = ax.plot(x, np.sin(x))

def update(w = 1.0):
    line.set_ydata(np.sin(w * x))
    plt.show()

interact(update)

代码生成的情节很好 - output

但是当我拖动滑块时,图形不会更新。关于为什么会这样的任何想法?

【问题讨论】:

    标签: python matplotlib jupyter-notebook data-visualization ipywidgets


    【解决方案1】:

    注意:您的代码实际上是开箱即用的,因此可能值得更新您的依赖项,看看是否能解决问题。

    但是,您要更改的主要内容是调用fig.canvas.draw() 而不是plt.show()

    %matplotlib notebook
    from ipywidgets import *
    import numpy as np
    import matplotlib.pyplot as plt
    
    x = np.linspace(0, 2 * np.pi)
    fig = plt.figure()
    ax = fig.add_subplot(1, 1, 1)
    line, = ax.plot(x, np.sin(x))
    
    def update(w = 1.0):
        line.set_ydata(np.sin(w * x))
        fig.canvas.draw()
    
    interact(update)
    

    使用 Ipympl

    还有一个基于小部件的笔记本后端(也适用于 jupyterlab):ipympl,您可以使用 pip install ipympl 安装它并使用 %matplotlib ipympl

    一般而言,ipympl 后端与笔记本后端相比,与其他小部件一起使用会更好。

    在 matplotlib 中使用 interactive

    interactive 的一个不幸后果是它假定每次滑块值更改时都会完全重新生成输出。这并不总是与您使用的 set_data 方法配合得非常好。因此,您最好手动生成和连接滑块。我还要注意,我编写了一个包,它使用set_data 命令自动连接小部件以更新matplotlib 图:https://mpl-interactions.readthedocs.io/en/stable/。使用该软件包,您的代码将是

    %matplotlib notebook
    import numpy as np
    import matplotlib.pyplot as plt
    import mpl_interactions.ipyplot as iplt
    
    x = np.linspace(0, 2 * np.pi, 1000)
    fig = plt.figure()
    ax = fig.add_subplot(1, 1, 1)
    
    def f(x, w):
        return np.sin(w * x)
    
    controls = iplt.plot(x, f, w=(1, 10))
    

    【讨论】:

    • mpl_interactions 包非常棒。解决了双重(甚至三重)显示问题,而且速度快如闪电。干得好!
    【解决方案2】:

    这样就可以了。

    # load the interactive tool
    from ipywidgets import interact, interactive, widgets, fixed
    try:
        from ipywidgets import Layout
    except:
        pass 
    
    import numpy as np
    import matplotlib.pyplot as plt
    %matplotlib notebook
    
    def fta(freq = 50.0):
        "showing sine frequency"
        y = np.sin(freq*x)
        f, ax1 = plt.subplots(nrows=1,figsize=(8,6))
        ax1.plot(x[0:100], y[0:100],'b')
        ax1.set_ylim(ymin=-1.1, ymax=1.1)
        ax1.grid();
        # then use it interactively,
    interactive( fta, freq=(0.0,100.0))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多