diff --git a/GettingStarted-02-InteractiveVisualization.ipynb b/GettingStarted-02-InteractiveVisualization.ipynb index aad575a..432438c 100644 --- a/GettingStarted-02-InteractiveVisualization.ipynb +++ b/GettingStarted-02-InteractiveVisualization.ipynb @@ -1,427 +1,429 @@ { "cells": [ { "cell_type": "markdown", "id": "42235b78-7365-4921-8034-a7139a839952", "metadata": { "toc-hr-collapsed": true }, "source": [ "# Workshop \"Teaching Sciences and Engineering with Jupyter Notebooks\" 2022\n", "C. Hardebolle, [CC-BY-NC-SA 4.0](https://creativecommons.org/licenses/by-nc-sa/4.0/)\n", "\n", "
\n", " How to use this notebook?
\n", " This notebook is made of text cells and code cells. The code cells have to be executed to see the result of the program.
To execute a cell, simply select it and click on the \"play\" button () in the tool bar just above the notebook, or type shift + enter.
It is important to execute the code cells in their order of appearance in the notebook.\n", "
" ] }, { "cell_type": "markdown", "id": "a2774ae7-2192-4acc-9b04-39a894706ab5", "metadata": {}, "source": [ "# Tutorial: creating interactive visualizations with Matplotlib\n", "\n", "This very short tutorial walks you through the steps for creating an interactive visualization with matplotlib. \n", "Please note that there are *multiple ways* to achieve the same result. This tutorial is just one possible example." ] }, { "cell_type": "markdown", "id": "a7ecbc64-f2c7-4066-ab9c-eeabe7675d06", "metadata": {}, "source": [ "## Technical setup" ] }, { "cell_type": "markdown", "id": "2ca6f8ff-3012-47f2-8f91-f0c05c4ec0a7", "metadata": {}, "source": [ "We need to import two libraries: \n", "* matplotlib for plotting\n", "* ipywidgets for interaction elements such as sliders" ] }, { "cell_type": "code", "execution_count": null, "id": "178a7a7c-86dd-4bad-80ee-70c250708b82", "metadata": {}, "outputs": [], "source": [ "import matplotlib.pyplot as plt\n", "import ipywidgets as widgets" ] }, { "cell_type": "markdown", "id": "8322fb56-37f2-45b0-9c40-2ddfa29eb4b6", "metadata": {}, "source": [ "Before starting to construct a figure, we need to tell matplotlib what we want to generate:\n", "* static images: `%matplotlib inline`\n", "* or dynamic interactive visuals: `%matplotlib widget`" ] }, { "cell_type": "code", "execution_count": null, "id": "2f42895d-8a0a-41b9-aca7-118ed0c476cd", "metadata": {}, "outputs": [], "source": [ "# In this tutorial, we will create an interactive figure\n", "%matplotlib widget" ] }, { "cell_type": "markdown", "id": "c7a1a710-02f9-4ce0-b546-6422f2db7549", "metadata": {}, "source": [ "This setting changes the type of `backend` that matplotlib will use. \n", "With the static backend, matplotlib will generate a new image each time we make a modification. \n", "With the interactive backend, only one image will be generated and all the actions and drawings will update the image. \n", "\n", "*Watchout: code written with one backend usually does not work with another backend!*" ] }, { "cell_type": "markdown", "id": "568a1cf2-9745-4396-8575-4d245dfa125a", "metadata": {}, "source": [ "## Data to generate the visualization\n", "Let's generate some data to plot. \n", "In this example we will draw a house and its roof, using sets of x and y coordinates to define points connected by a line." ] }, { "cell_type": "code", "execution_count": null, "id": "29922ff8-37d4-4b1e-9cf6-9fa5d25975c1", "metadata": {}, "outputs": [], "source": [ "# We will plot a rectangle to model a house\n", "house_x = [2, 2, 4, 4]\n", "house_y = [0, 2, 2, 0]\n", "\n", "# We will plot a triangle to model the roof\n", "roof_x = [2, 3, 4]\n", "roof_y = [2, 5, 2]" ] }, { "cell_type": "markdown", "id": "fea1da5d-f18d-48f4-8b4f-e24d3d1cb745", "metadata": {}, "source": [ "## Building the visualization" ] }, { "cell_type": "markdown", "id": "b0530b84-7d3d-4e65-9960-e222f434686f", "metadata": {}, "source": [ "Before starting to build the figure, we first tell matplolib to wait until we tell him to show the figure where we want in the notebook. \n", "If we don't do that, it will start to display the figure right after the first instructions we write." ] }, { "cell_type": "code", "execution_count": null, "id": "9d65ead3-efc7-40f5-823a-306980328261", "metadata": {}, "outputs": [], "source": [ "# Turn the output off for the moment\n", - "plt.ioff()" + "plt.ioff();" ] }, { "cell_type": "markdown", "id": "22c696c5-f1bb-48cc-b68a-286bea11396e", "metadata": {}, "source": [ "Now let's build the plot. It has two main components:\n", "* a figure, which is an overall container\n", "* one or more \"axes\" i.e. plots" ] }, { "cell_type": "code", "execution_count": null, "id": "f99f07ce-f750-493e-bac0-76427ac83ffb", "metadata": {}, "outputs": [], "source": [ "# Creation of the figure\n", "fig = plt.figure(num='Interactive figure', figsize=(6,4))\n", "\n", "# Creation of one subplot/axe - it will take position index number 1 in a grid of 1 row and 1 column, as described by (nrows, ncols, index)\n", "ax = fig.add_subplot(1,1,1)" ] }, { "cell_type": "markdown", "id": "19d36c78-ecb3-4f17-8199-a48437331805", "metadata": {}, "source": [ "Once we have created these components, we can plot our data. \n", "The `plot` method of the `axe` object plots y versus x as lines and/or markers. It returns the resulting `line` object(s)." ] }, { "cell_type": "code", "execution_count": null, "id": "a061a2e0-1775-4752-8884-88bf00639903", "metadata": {}, "outputs": [], "source": [ "# Plot the house\n", "ax.plot(house_x, house_y)\n", "\n", "# Plot the roof, and get the resulting line, on which we will add interactivity later - NOTICE the syntax with the comma \"roof_line, =\"\n", "roof_line, = ax.plot(roof_x, roof_y)" ] }, { "cell_type": "markdown", "id": "69412705-47f2-40b3-9cd0-95422a0b6309", "metadata": {}, "source": [ "Now let's show the resulting figure! \n", "For that we need to turn on again the interactive mode of matplotlib." ] }, { "cell_type": "code", "execution_count": null, "id": "d940f221-813c-4f52-8fa3-766fd0fa9b2f", "metadata": {}, "outputs": [], "source": [ "# Turn the output on\n", "plt.ion()\n", "\n", "# Show the figure\n", "display(fig.canvas)" ] }, { "cell_type": "markdown", "id": "425f9a44-f36b-417b-a9de-35e855bd5487", "metadata": {}, "source": [ "## Adding some interactivity \n", "Now we can add some interactivity to this plot. For that, we proceed in four steps:\n", "1. We create a slider" ] }, { "cell_type": "code", "execution_count": null, "id": "eadae473-19a9-4f18-b453-4aec54012015", "metadata": {}, "outputs": [], "source": [ "# We create a slider with values ranging from 2 to 10 in steps of .5, by default on value 5\n", "roof_widget = widgets.FloatSlider(min=2, max=10, step=0.5, value=5, description='Roof height:')" ] }, { "cell_type": "markdown", "id": "37549dfa-026c-4ee2-9c45-5e55b06f84b8", "metadata": {}, "source": [ "2. We create a function that will be called when the slider is moved and will update the figure" ] }, { "cell_type": "code", "execution_count": null, "id": "93c29bff-d13f-477f-ab8d-9723856472b1", "metadata": {}, "outputs": [], "source": [ "# This function will be called when the slider is moved\n", "def roof_event_handler(change):\n", " # It allows us to retrieve the new value of the slider\n", " newposition = change.new\n", "\n", " # Then we can update the points of the roof line\n", " roof_line.set_ydata([2, newposition, 2])\n", " \n", - " # If the interactive mode of matplotlib is on (as it actually is in our case), we don't need to tell the figure to update the drawing\n", - " # But if it is off, just uncomment the line below so that the figure is updated\n", - " #fig.canvas.draw()" + " # Finally we tell the figure to draw the changed parts\n", + " fig.canvas.draw_idle()" ] }, { "cell_type": "markdown", "id": "bfc19f67-fd2a-4d99-a138-3e84c25a962b", "metadata": {}, "source": [ "3. We link the slider to the callback function" ] }, { "cell_type": "code", "execution_count": null, "id": "c7155220-f5f2-40f4-aad6-38d055441646", "metadata": {}, "outputs": [], "source": [ "# Finally we link the widget to the callback function \n", "roof_widget.observe(roof_event_handler, names='value')" ] }, { "cell_type": "markdown", "id": "3242d42a-706b-4040-bf08-a2d118829ab4", "metadata": {}, "source": [ "4. And then we display both the figure and the slider" ] }, { "cell_type": "code", "execution_count": null, "id": "9ebd1106-589f-46ad-b7cd-bfce1db0744a", "metadata": {}, "outputs": [], "source": [ "# Display the figure again, and the widget below (no need to turn the interactive mode on again since we did it earlier)\n", "display(fig.canvas, roof_widget)" ] }, { "cell_type": "markdown", "id": "03b9a626-ee0a-4bec-ba57-d2691252d881", "metadata": {}, "source": [ "Note that the slider udpates both the figure here and also the figure above. \n", "This is the work of the interactive backend!" ] }, { "cell_type": "markdown", "id": "e6c31f99-06b2-42a5-988f-a8e81951b6e2", "metadata": {}, "source": [ "---\n", "\n", "# Your turn now!" ] }, { "cell_type": "markdown", "id": "b4c41719-fe79-4c76-ba62-68e5fbb3edc1", "metadata": {}, "source": [ "
\n", " Activity
\n", "\n", "Add a line to the plot that draws a door to the house. \n", "Then create a slider that will let the user choose the width of the door. \n", " \n", "
" ] }, { "cell_type": "markdown", "id": "206b7ae1-02b9-44d0-9af9-4472df30adbe", "metadata": {}, "source": [ "
\n", "\n", "**Solution** - You can see *one possible solution* by clicking on the \"...\" below.\n", " \n", "
" ] }, { "cell_type": "code", "execution_count": null, "id": "15d0e85e-abc0-4ff1-af59-47eb4c19869b", "metadata": { "jupyter": { "source_hidden": true }, "tags": [] }, "outputs": [], "source": [ "# First define the x and y coordinates of the door\n", "door_x = [2.25, 2.25, 2.50, 2.50]\n", "door_y = [0, 1, 1, 0]\n", "\n", "# Draw the door on the plot and get the resulting line (to be able to update it with the slider)\n", "door_line, = ax.plot(door_x, door_y)\n", "\n", "# Create a widget for the width of the door\n", "door_widget = widgets.FloatSlider(min=0.25, max=1.5, step=0.05, value=0.25, description='Door width:')\n", "\n", "# This function will be called when the door slider is moved\n", "def door_event_handler(change):\n", " # It allows us to retrieve the new value of the slider\n", " newwidth = change.new\n", "\n", - " # Then we can change the points of the door line - the figure will update automatically thanks to the interactive mode!\n", + " # Then we can change the points of the door line\n", " door_line.set_xdata([2.25, 2.25, 2.25+newwidth, 2.25+newwidth])\n", " \n", + " # Finally we tell the figure to draw the changed parts\n", + " fig.canvas.draw_idle()\n", + " \n", "\n", "# Finally we link the widget to the callback function \n", "door_widget.observe(door_event_handler, names='value')\n", "\n", "# Let's display again the whole figure with the two sliders\n", "display(fig.canvas, roof_widget, door_widget)" ] }, { "cell_type": "markdown", "id": "9690331e-446d-4062-97d0-069276e335bf", "metadata": {}, "source": [ "---\n", "\n", "# Additional resources\n", "\n", "More on figures and axes of Matplotlib: \n", "https://medium.com/@kapil.mathur1987/matplotlib-an-introduction-to-its-object-oriented-interface-a318b1530aed\n", "\n", "Using the widgets to add interactivity: \n", "https://ipywidgets.readthedocs.io/en/latest/examples/Widget%20Events.html\n", "\n", "Details about the backends of matplotlib: \n", "https://matplotlib.org/3.4.3/users/interactive.html" ] } ], "metadata": { "kernelspec": { - "display_name": "Python 3 (ipykernel)", + "display_name": "Python", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.8.10" } }, "nbformat": 4, "nbformat_minor": 5 } diff --git a/GettingStarted-03-InteractiveVisualizationHiddenCode.ipynb b/GettingStarted-03-InteractiveVisualizationHiddenCode.ipynb index 8bc7e4c..f25f412 100644 --- a/GettingStarted-03-InteractiveVisualizationHiddenCode.ipynb +++ b/GettingStarted-03-InteractiveVisualizationHiddenCode.ipynb @@ -1,171 +1,169 @@ { "cells": [ { "cell_type": "markdown", "id": "4a8ba901-956b-49da-88f3-7a41036c4dbc", "metadata": { "toc-hr-collapsed": true }, "source": [ "# Workshop \"Teaching Sciences and Engineering with Jupyter Notebooks\" 2022\n", "C. Hardebolle, [CC-BY-NC-SA 4.0](https://creativecommons.org/licenses/by-nc-sa/4.0/)\n", "\n", "
\n", " How to use this notebook?
\n", " This notebook is made of text cells and code cells. The code cells have to be executed to see the result of the program.
To execute a cell, simply select it and click on the \"play\" button () in the tool bar just above the notebook, or type shift + enter.
It is important to execute the code cells in their order of appearance in the notebook.\n", "
" ] }, { "cell_type": "markdown", "id": "37abfac0-d5d8-44be-8572-425abf875a19", "metadata": {}, "source": [ "# Demo: hiding the code of your interactive visualizations\n", "\n", "This notebook demonstrates how the code from an interactive visualization can be hidden from a notebook. \n", "Again there are different ways to achieve the same result, this is only one possible solution.\n", "\n", "In this demo, we use the same \"interactive house\" visualization example as [in this notebook](GettingStarted-02-InteractiveVisualization.ipynb)." ] }, { "cell_type": "markdown", "id": "c0c4751d-38b6-449b-8db2-8699e51a8eba", "metadata": {}, "source": [ "## Putting the code in an external Python file\n", "The main principle is to put the code that generates the interactive visualization into an external Python file. \n", "In such a file, code can take the form of functions or classes.\n", "\n", "Here is an exemple: [interactivevisualization.py (click here to open the file)](lib/interactivevisualization.py). \n", "In this demo, we have simply created a function that generates the interactive house visualization and displays it. " ] }, { "cell_type": "markdown", "id": "c0e26a53-bc03-429f-aeb0-71abb560f549", "metadata": { "tags": [] }, "source": [ "## Using the file\n", "To be able to use the code defined in our Python file, we simply use the built-in `import` feature of Python." ] }, { "cell_type": "code", "execution_count": null, "id": "8aa8717e-44e5-4df6-b79f-0f6e01488d9c", "metadata": {}, "outputs": [], "source": [ "# Let's import the content of our Python file\n", "from lib.interactivevisualization import *" ] }, { "cell_type": "markdown", "id": "b0c5c5ec-6a13-4bd7-aa39-d2531010c0bf", "metadata": {}, "source": [ "Then we can simply call the function we have defined." ] }, { "cell_type": "code", "execution_count": null, "id": "a15eab91-850b-4402-b8fa-a244fbce9f70", "metadata": {}, "outputs": [], "source": [ "# Now we can use the functions defined in the file\n", "displayInteractiveHouse()" ] }, { "cell_type": "markdown", "id": "1c44abd2-1641-42e7-b7eb-c5e14c77251c", "metadata": {}, "source": [ "---\n", "\n", "## Differences between the code in the notebook and in the external file\n", "\n", "### Choosing the matplotlib backend\n", "\n", "We cannot use the instruction `%matplotlib widget` to choose the backend of matplotlib in a Python file because it works only when in a [notebook](02-InteractiveVisualization.ipynb). \n", "Instead we need to use the following two lines, which do exactly the same thing:\n", "```python\n", "from IPython import get_ipython\n", "get_ipython().run_line_magic('matplotlib', 'widget')\n", "\n", "```\n", "\n", "### Turning the interactive mode on/off\n", "\n", "Since the code is in one piece only - compared to split over several cells in a [notebook](02-InteractiveVisualization.ipynb) - we don't need to switch the interactive mode of matplotlib off and back on again. \n", "Matplotlib will simply render the full visualization in one shot when the function is called.\n", "\n", - "Therefore, we don't need to:\n", + "Therefore, we **don't need to**:\n", "- call `plt.ioff()` to turn the interactive mode off\n", "- call `plt.ion()` to turn it back on\n", "- display the figure explicitely (`display(fig.canvas)`) - matplotlib will display it automatically while it is drawn\n", "\n", "NB: try it out, if you display the figure, you will see the figure twice..." ] }, { "cell_type": "markdown", "id": "1bd36fc9-b9cd-464a-acd1-d2b574cc59a7", "metadata": {}, "source": [ "---\n", "\n", "## Function or class?\n", "\n", "Note that, in this design, the event handler function becomes a *nested* function, which some would argue is not a great design. \n", "Another way to achieve the same thing is to create a class with the different variables of the visualization as attributes and the event handler function as a method. \n", "For this, you need to be familiar with [object-oriented programming in Python](https://realpython.com/python3-object-oriented-programming/). \n", "\n", "Here is an example of a more complex visualization example implemented as a Python class: [SuspendedObject.py (click here to open the file)](SuspendedObject.py). \n", "\n", "Execute the code cell below to see the result. \n", "Note that once you have executed this cell, the previous visualization will not work anymore since the interactive backend renders only one visualization at a time. \n", "This is actually one limitation of the interactive backend." ] }, { - "cell_type": "code", - "execution_count": null, - "id": "f9c64f8d-33a6-4156-86d8-ad34598e2b8d", + "cell_type": "raw", + "id": "41519f8f-2645-4e5c-ad0e-b2cda51bb3bf", "metadata": {}, - "outputs": [], "source": [ "from lib.suspendedobjectinteractive import *\n", "SuspendedObjectLab();" ] } ], "metadata": { "kernelspec": { - "display_name": "Python 3 (ipykernel)", + "display_name": "Python", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.8.10" } }, "nbformat": 4, "nbformat_minor": 5 } diff --git a/lib/interactivevisualization.py b/lib/interactivevisualization.py index a9db468..3097178 100644 --- a/lib/interactivevisualization.py +++ b/lib/interactivevisualization.py @@ -1,48 +1,52 @@ import matplotlib.pyplot as plt import ipywidgets as widgets # Enable interactive backend for matplotlib from IPython import get_ipython get_ipython().run_line_magic('matplotlib', 'widget') def displayInteractiveHouse(): # We will plot a rectangle to model a house house_x = [2, 2, 4, 4] house_y = [0, 2, 2, 0] # We will plot a triangle to model the roof roof_x = [2, 3, 4] roof_y = [2, 5, 2] - # Creation of the figure fig = plt.figure(num='Interactive figure', figsize=(6,4)) # Creation of one subplot/axe - it will take position index number 1 in a grid of 1 row and 1 column, as described by (nrows, ncols, index) ax = fig.add_subplot(1,1,1) # Plot the house ax.plot(house_x, house_y) # Plot the roof, and get the resulting line, on which we will add interactivity later - NOTICE the syntax with the comma "roof_line, =" roof_line, = ax.plot(roof_x, roof_y) # We create a slider with values ranging from 2 to 10 in steps of .5, by default on value 5 roof_widget = widgets.FloatSlider(min=2, max=10, step=0.5, value=5, description='Roof height:') + # This function will be called when the slider is moved def roof_event_handler(change): # It allows us to retrieve the new value of the slider newposition = change.new - # Then we can change the points of the door line - the figure will update automatically thanks to the interactive mode! + # Then we can change the points of the door line roof_line.set_ydata([2, newposition, 2]) - + + # Finally we tell the figure to draw the changed parts + fig.canvas.draw_idle() + + # Finally we link the widget to the callback function roof_widget.observe(roof_event_handler, names='value') # The figure is automatically displayed since matplotlib is in interactive mode (if we display it explicitely, it will show up twice!) # We only need to display the widget display(roof_widget)