IPython Notebook widgets for Matplotlib interactivity

后端 未结 3 741
悲&欢浪女
悲&欢浪女 2021-02-06 00:05

I would like to use the ipython notebook widgets to add some degree of interactivity to inline matplotlib plots.

In general the plot can be quite heavy and I want to on

3条回答
  •  半阙折子戏
    2021-02-06 00:37

    The solution turns out to be really simple. To avoid showing the first figure we just need to add a close() call before the interact call.

    Recalling the example of the question, a cell like this will correctly show a single interactive figure (instead of two):

    fig, ax = plt.subplots()
    ax.plot([3,1,2,4,0,5,3,2,0,2,4])
    plt.close(fig)
    
    vline = ax.axvline(1)
    hline = ax.axhline(0.5)
    
    def set_cursor(x, y):
        vline.set_xdata((x, x))
        hline.set_ydata((y, y))
        display(fig)
    
    interact(set_cursor, x=(1, 9, 0.01), y=(0, 5, 0.01))
    

    A cleaner approach is defining the function add_cursor (in a separate cell or script):

    def add_cursor(fig, ax):
        plt.close(fig)
    
        vline = ax.axvline(1, color='k')
        hline = ax.axhline(0.5, color='k')
    
        def set_cursor(x, y):
            vline.set_xdata((x, x))
            hline.set_ydata((y, y))
            display(fig)
    
        interact(set_cursor, x=ax.get_xlim(), y=ax.get_ylim())
    

    and then call it whenever we want to add an interactive cursor:

    fig, ax = plt.subplots()
    ax.plot([3,1,2,4,0,5,3,2,0,2,4])
    add_cursor(fig, ax)
    

提交回复
热议问题