Ipywidgets

Ipywidgets#

If you publish widgets in a jupyter book they might (depending on your implementation) require an active python kernel for the output to be interactive. Using the thebe-integration, this is possible. Note: You can circumvent the use of a kernel by using packages which don’t need such a kernel, for example the non-kernel-based widgets using Plotly.

matplotlib widgets#

When you’d like to use ipywidgets in combinations with a matplotlib figure, import the following packages:

import ipywidgets as widgets
import micropip
await micropip.install("ipympl")

Activate the correct output format:

%matplotlib widget

Write the code which generates your plot in a function:

fig = plt.figure()  # Define the figure once
ax = fig.add_subplot(1,1,1)       # Define the axis once

def update_plot(input_variables_from_widget):
    ax.clear()   # Clear the existing plot
    ax.plot(x,y) # Plot your actual data
    plt.draw()   # Update the plot whenever this function is executed

Initiate the widget:

input_slider = widgets.FloatSlider(value=0, min=0, max=10, step=1, description='Input variable:') # Defines a widget, more options than just FloatSlider
widgets.interact(update_plot, input_variable_from_widget = input_slider);

Finally, When using %matplotlib widget, there’s the following toolbar:

Which only shows up when you hoover above. If you want to disable the toolbar you can use:

fig = plt.gcf()
fig.canvas.toolbar_visible = False

If you want it to be visible even if you don’t hoover above it, use:

fig = plt.gcf()
fig.canvas.toolbar_visible = True

Please note:

  • You might want to hide the output before the thebe has been activated.

  • You can hide the code by adding a custom-made tag: thebe-remove-input-init.

  • You can automatically start the thebe functionality when you add auto-execute-page to a cell.

Example#

The code below shows an example of the strain energy in a structure and work done by a force for different trial functions. Because of the actual python code, the plot ‘refreshes’ upon updating a widgets. This can be avoided by updating the current figure instead of plotting a new figure. Remember, first press –> Live Code and then wait until all cells are executed:

The graph will appear below in interactive mode: