0

I wanted to learn how to use interactive plots in Jupyter Notebook and created a script that updates a figure based on the current values of two sliders. The idea is simply that when the value of one of the sliders changes the figure should be updated.
This worked fine when I first ran the code on my Windows PC (using Windows 10). However, when I then ran the same code on my MacBook (using macOS Monterey 12.6.1), the figure is not updated but a new figure is created every time I change the value of one of my sliders.
Please find a MWE below:

import numpy as np
import matplotlib.pyplot as plt
import ipywidgets as widgets
%matplotlib widget

# Create two sliders
slider1 = widgets.IntSlider(value=4, min=0, max=10, step=1,
                            description='Slider1', continuous_update = False)

slider2 = widgets.IntSlider(value=8, min=0, max=10, step=1, 
                            description='Slider2', continuous_update = False)

# Some function that plots the result based on the current values of the sliders
def plotResult(a, b):
    plt.close('all')
    plt.figure()
    plt.hlines(a+b, xmin=0, xmax=10)
    
# Create interactive plot
interactive_plot = widgets.interactive_output(plotResult, {"a":slider1, "b":slider2})
ui = widgets.HBox([slider1, slider2])
display(ui, interactive_plot)

When I run the above code in a cell in my Jupyter Notebook, I get the following output: (https://i.stack.imgur.com/NX02T.png).
When I now change any of the sliders, on Windows my figure is "updated in-place", while on macOS a new figure is created everytime (every figure newly created figure is labeled as 'Figure 1'). I don't understand why this is happening as I explicitly close all currently opening figures at the beginning of plotResults(a,b) by using the command plt.close('all').

I thought that since every newly created figure on macOS is labeled 'Figure 1' the problem could be that on macOS the cells are not refreshed. Thus, I additionally imported the module IPython using import IPython and then added the command IPython.display.clear_output(wait=True) after the first line of plotResults(a,b). However, this did not work and the problem persisted.
I also tried to use a different Matplotlib backend such as %matplotlib ipympl or %matplotlib nbagg instead of %matplotlib widget but this also did not help anything.

dennis
  • 1

0 Answers0