0

The following code refreshes the bar plot whenever the slider is moved

from ipywidgets import widgets
import pandas as pd
import matplotlib.pyplot as plt

slider = widgets.IntSlider(value=0,min=0,max=100,step=1,continuous_update=False)

def run_model(slider):
  df = pd.DataFrame({"label":["A","B","C"],"value":[0,slider,100]})
  fig,ax = plt.subplots(1,1,figsize=(3,2))
  df.plot.bar(ax=ax)
  plt.show()
  
output = widgets.interactive_output(run_model, {"slider":slider})
display(slider,output)

However without the plt.show() line, the output is appended rather than replaced (not desirable behaviour!), I think because the plot is sent to the Jupyter cell output rather than the (freshly cleared) ipywidgets output.

Why is it necessary to call plt.show() to achieve a refresh, and furthermore why does it change where the plot has gone after it's already been produced by df.plot?

Sideshow Bob
  • 4,566
  • 5
  • 42
  • 79
  • see https://stackoverflow.com/a/44329309/7758804 and https://stackoverflow.com/a/45694414/7758804 – Trenton McKinney Apr 17 '23 at 17:17
  • Also, you should be using [jupyter lab](https://jupyterlab.readthedocs.io/en/stable/) or update jupyter notebook, as [this is not reproducible](https://i.stack.imgur.com/vxiSC.png). [Migrating to Notebook 7](https://jupyter-notebook.readthedocs.io/en/latest/migrate_to_notebook7.html). If you are using Anaconda, then jupyter lab is likely already installed. `conda update --all`. Invoke `jupyter lab` at the anaconda prompt instead of `jupyter notebook`. – Trenton McKinney Apr 17 '23 at 17:24

0 Answers0