Search code examples
pythonmatplotlibjupyter-labipywidgets

How do you plot on a premade matplotlib plot with IPyWidgets?


I have a scenario where I would like to initialize the plot and plot a bunch of stuff on it before I run a widget on it. However, the jupyter widget refuses to plot on my already made plot. Instead, nothing shows up. A simplified example of this is below.

import matplotlib.pyplot as plt
import ipywidgets as widgets
from IPython import display 

fig=plt.figure(1,(2,2))
axs=fig.gca()

def testAnimate(x):
    axs.text(0.5,0.5,x)

xs=widgets.IntSlider(min=0,max=3,value=1) #Create our intslider such that the range is [1,50] and default is 10

gui = widgets.interactive(testAnimate, x=xs) #Create our interactive graphic with the slider as the argument
display.display(gui)    #display it

I would expect the value of x to show up on axs, but it does not. I realize that in this case I could just do plt.text, however in my actual project that is not viable. So, how do I get the value of x to show up on my plot?

Thanks!


Solution

  • Assuming that you are using Jupyter Notebook, you first have to initialize the interactive matplotlib. You can do that by running either one of the following magic commands:

    • %matplotlib notebook
    • %matplotlib widget. This one requires ipympl to be installed.

    Then, execute:

    import matplotlib.pyplot as plt
    import ipywidgets as widgets
    from IPython import display 
    
    fig, ax = plt.subplots()
    text = ax.text(0.5, 0.5, "0")
    
    def testAnimate(x):
        text.set_text(x)
    
    xs=widgets.IntSlider(min=0,max=3,value=1) #Create our intslider such that the range is [1,50] and default is 10
    
    gui = widgets.interactive(testAnimate, x=xs) #Create our interactive graphic with the slider as the argument
    display.display(gui)    #display it