diff --git a/book/features/widgets.ipynb b/book/features/widgets.ipynb index 369c08b..f63bbcc 100644 --- a/book/features/widgets.ipynb +++ b/book/features/widgets.ipynb @@ -6,7 +6,35 @@ "source": [ "# Widgets\n", "\n", - "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](live_code.md), 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](interactive_element)." + "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](live_code.md), 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](interactive_element).\n", + "\n", + "## `matplotlib` widgets\n", + "When you'd like to use `ipywidgets` in combinations with a `matplotlib` figure, import the following packages:\n", + "```{python}\n", + "import ipywidgets as widgets\n", + "import micropip\n", + "await micropip.install(\"ipympl\")\n", + "```\n", + "Activate the correct output format:\n", + "```{python}\n", + "%matplotlib widget\n", + "```\n", + "\n", + "Write the code which generates your plot in a function:\n", + "```{python}\n", + "fig = plt.figure() # Define the figure once\n", + "ax = fig.add_subplot(1,1,1) # Define the axis once\n", + "\n", + "def update_plot(input_variables_from_widget):\n", + " ax.clear() # Clear the existing plot\n", + " ax.plot(x,y) # Plot your actual data\n", + " plt.draw() # Update the plot whenever this function is executed\n", + "```\n", + "Initiate the widget:\n", + "```{python}\n", + "input_slider = widgets.FloatSlider(value=0, min=0, max=10, step=1, description='Input variable:') # Defines a widget, more options than just FloatSlider\n", + "widgets.interact(update_plot, input_variable_from_widget = input_slider);\n", + "```\n" ] }, {