Jupyter Notebook: interactive plot with widgets

后端 未结 2 1773
野性不改
野性不改 2020-12-02 17:11

I am trying to generate an interactive plot that depends on widgets. The problem I have is that when I change parameters using the slider, a new plot is done after the previ

相关标签:
2条回答
  • 2020-12-02 17:45

    This is an issue (?) introduced in the last version of jupyter and/or ipywidgets. One workaround I found was to add the line plt.show() at the end of plot_func.

    0 讨论(0)
  • 2020-12-02 17:54

    As you want to change the figure, instead of creating a new one, may I suggest the following way:

    1. Use an interactive backend; %matplotlib notebook
    2. Update the line in the plot, instead of drawing new ones.

    So the code could look something like this:

    %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_idle()
    
    interact(update);
    

    Alternatively you may use plt.show() as in this answer.

    0 讨论(0)
提交回复
热议问题