J_yang
J_yang

Reputation: 2812

Jupyter, ipywidgets, how to refresh plot using dropdown menu

I have a dropdown to that plot specific data range based on the dropdown value. However, it keeps creating new plot to the output rather than refreshing the same plot. Please help, here is a cell. I looked up a post that I can do the plotting within an Output but it doesn't seem to do anything.

from IPython.display import clear_output
out = widgets.Output()    
w = widgets.Dropdown(
    options=alist,
    description='List',
)
ax = plt.figure()


def on_change(change):
    global ax
    if change['name'] == 'value' and (change['new'] != change['old']):
        with out:
            ax = sns.boxplot(data = mydata[change['new']])
            plt.show()

w.observe(on_change)

display(w)
out

Upvotes: 0

Views: 7595

Answers (1)

Y. Luo
Y. Luo

Reputation: 5722

For the specific package versions I've tried, ipywidgets capturing output doesn't seem to work well with matplotlib. I'm not sure if this is relevant but there is an old issue mentioned in 2017. One viable solution is to use clear_output to clear all outputs and redraw everything like this:

from IPython.display import display, clear_output
import ipywidgets as widgets
import seaborn as sns

mydata = {'a': range(3),
          'b': range(4),
          'c': range(5)}
default = 'b'
sns.boxplot(data=mydata[default])

w = widgets.Dropdown(
    options=mydata.keys(),
    value = default,
    description='List',
)
display(w)

def on_change(change):
    if change['name'] == 'value' and (change['new'] != change['old']):
        clear_output()
        display(w)
        sns.boxplot(data = mydata[change['new']])

w.observe(on_change)

When selecting/changing the dropdown, the output will "flash" when the whole thing is cleared and redrawn. I hope this fits your specific use case.

My package versions are:

ipykernel                 5.1.0            py37h39e3cac_0  
ipython                   7.2.0            py37h39e3cac_0  
ipython_genutils          0.2.0                    py37_0  
ipywidgets                7.4.2                    py37_0  

jupyter                   1.0.0                    py37_7  
jupyter_client            5.2.3                    py37_0  
jupyter_console           6.0.0                    py37_0  
jupyter_core              4.4.0                    py37_0  

matplotlib                3.0.2            py37h5429711_0  

seaborn                   0.9.0                    py37_0  

widgetsnbextension        3.4.2                    py37_0  

Upvotes: 7

Related Questions