{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "## How to Use iPython Widgets in A Jupyter Notebook" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Author:** Becky Vandewalle (rcv3@illinois.edu)\n", "
**Created:** May 10, 2021\n", "
**Last Updated:** May 19, 2021\n", "\n", "This notebook introduces iPython widgets and demonstrates simple ways to use them." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Contents\n", "- [Imports](#import)\n", "- [What is a widget?](#what_is)\n", "- [Common widget types](#common)\n", "- [Handling simple widget events](#simple_event) - skip to here if you are familiar with available widgets\n", "- [Using Widgets with Folium Maps](#folium)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "### Imports" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Important!** You must run the next cell so that all the code examples in this notebook work." ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "# import required libraries\n", "import ipywidgets as widgets\n", "import matplotlib.pyplot as plt" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "### What is a widget?" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "A widget is an object that can be used to get information to or from someone who is using a Jupyter notebook without requiring them to insert or change code in a code cell. Some common widgets are buttons, sliders, and text boxes. This type of object is also called an \"event handler\", because it is an object that does something when an event, such as a mouse click or pressing a key, happens.\n", "\n", "This is a simple overview of some common widgets. For more detailed information, refer to documentation [here](https://ipywidgets.readthedocs.io/en/latest/index.html). Some of the examples in this tutorial are based off an widget introduction found at https://ipywidgets.readthedocs.io/en/latest/examples/Widget%20Basics.html." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Simple widget examples" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You can see a simple widget by running the next code cell. The first line creates a widget and the second line displays it. Click on the slider's circle and drag it. What happens to the number on the right when you do this?" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "b298ba2e8cc441fcb214a1ee3f889344", "version_major": 2, "version_minor": 0 }, "text/plain": [ "IntSlider(value=0)" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "w = widgets.IntSlider()\n", "display(w)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now that we have a widget object, `w`, we can print the value:" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "0" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "w.value" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Note that when if you display the value and then change the slider the printed value does not also change. However, you can display dynamic text by linking the slider widget to a text widget as shown below. " ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "527415ced7f74a34a02a6aa6b426cbd1", "version_major": 2, "version_minor": 0 }, "text/plain": [ "IntSlider(value=0)" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "ea72ecdca46d4fed8e2de255edb7442a", "version_major": 2, "version_minor": 0 }, "text/plain": [ "FloatText(value=0.0)" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "s = widgets.IntSlider()\n", "t = widgets.FloatText()\n", "display(s, t)\n", "\n", "wlink = widgets.jslink((s, 'value'), (t, 'value'))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Notice that we have used `value` twice now. We can access it and other widget attributes through a list of keys that each widget has:" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "['_dom_classes', '_model_module', '_model_module_version', '_model_name', '_view_count', '_view_module', '_view_module_version', '_view_name', 'continuous_update', 'description', 'description_tooltip', 'disabled', 'layout', 'max', 'min', 'orientation', 'readout', 'readout_format', 'step', 'style', 'value']\n" ] } ], "source": [ "print([i for i in w.keys])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can use these keys to pass information to a widget when creating it as in the below example. If you disable a widget the value will not be able to be changed by interacting directly with the widget." ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "ebfcc479c8d34d13b9e411ccc7a542d2", "version_major": 2, "version_minor": 0 }, "text/plain": [ "Text(value='This is some text!', disabled=True)" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "", "version_major": 2, "version_minor": 0 }, "text/plain": [ "IntSlider(value=29, disabled=True)" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "tx = widgets.Text(value='This is some text!', disabled=True)\n", "wd = widgets.IntSlider(value=29, disabled=True)\n", "display(tx, wd)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Even if a widget is disabled, however, the value can be changed programatically by assigning a different number to the widget value. " ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "30" ] }, "execution_count": 7, "metadata": {}, "output_type": "execute_result" } ], "source": [ "wd.value=30\n", "wd.value" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Note that you can close a widget by calling `.close()`. This hides the widget but you can still access the widget's attirbutes." ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "30" ] }, "execution_count": 8, "metadata": {}, "output_type": "execute_result" } ], "source": [ "wd.close()\n", "wd.value" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "### Common widget types" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Here a few different common types of widgets will be displayed with some important values set. You can base new widgets off of these examples. For more details of available widgets, see the [widget list here](https://ipywidgets.readthedocs.io/en/latest/examples/Widget%20List.html)." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "One of the most important types of widgets is a basic button. It can be clicked, although nothing will happen until some code is linked to the button." ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "ebaf88a38892436ab04264372b12b1ab", "version_major": 2, "version_minor": 0 }, "text/plain": [ "Button(description='Click the button', style=ButtonStyle())" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "cb = widgets.Button(description='Click the button')\n", "\n", "display(cb)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "A slider is commonly used for numeric input." ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "42962de09b4a49bd895ac56de711e929", "version_major": 2, "version_minor": 0 }, "text/plain": [ "IntSlider(value=3, description='Slider', max=9, readout=False, step=3)" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "5d22327c1f13484494376d5611f9790b", "version_major": 2, "version_minor": 0 }, "text/plain": [ "FloatSlider(value=3.0, max=9.0, step=3.0)" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "889b7885aea44a9d95a6a5c404f71cff", "version_major": 2, "version_minor": 0 }, "text/plain": [ "FloatSlider(value=3.0, max=9.0, orientation='vertical', readout_format='.1f', step=3.0)" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "nsa = widgets.IntSlider(value=3, min=0, max=9, step=3, description='Slider', readout=False)\n", "nsb = widgets.FloatSlider(value=3, min=0, max=9, step=3)\n", "nsc = widgets.FloatSlider(value=3, min=0, max=9, step=3, orientation='vertical', readout_format='.1f')\n", "\n", "display(nsa, nsb, nsc)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Generally speaking, `Int` and `Float` can be used in the same place to specify the type of number wanted." ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "0d9903301ece4d6bbb981d8f6da64212", "version_major": 2, "version_minor": 0 }, "text/plain": [ "IntRangeSlider(value=(1, 2), max=10)" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "d32ca3735c0f4d789ec5c08e97e15fef", "version_major": 2, "version_minor": 0 }, "text/plain": [ "FloatRangeSlider(value=(6.0, 9.0), max=10.0)" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "nsd = widgets.IntRangeSlider(value=[1, 2], min=0, max=10)\n", "nse = widgets.FloatRangeSlider(value=[6, 9], min=0, max=10)\n", "\n", "display(nsd, nse)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Progress bars can also be very hand." ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [ { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "603edf79cbe04dbc9f1f39fcdc10e219", "version_major": 2, "version_minor": 0 }, "text/plain": [ "FloatProgress(value=6.5, max=10.0, style=ProgressStyle(bar_color='#eeaa00'))" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "pba = widgets.FloatProgress(value=6.5, min=0, max=10.0,\n", " style={'bar_color': '#eeaa00'})\n", "\n", "display(pba)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Sometimes it can be easier to select a number from a box." ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [ { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "ef1c3acc3d1a4fc4b8bdc1cb700fb300", "version_major": 2, "version_minor": 0 }, "text/plain": [ "BoundedIntText(value=9, max=10, min=7)" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "f18f7313268044319b474d4dcbadc6ac", "version_major": 2, "version_minor": 0 }, "text/plain": [ "IntText(value=9)" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "nta = widgets.BoundedIntText(value=9, min=7, max=10)\n", "ntb = widgets.IntText(value=9)\n", "display(nta, ntb)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Users can input a true or false value with a button or check box. The Valid widget is an easy way to indicate if input is valid or invalid." ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [ { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "8120f4c10962455799380dd0de0b651a", "version_major": 2, "version_minor": 0 }, "text/plain": [ "ToggleButton(value=False, description='Toggle!', tooltip='click to change')" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "99d15d1ee7f84f8fbc80c0cd74801bab", "version_major": 2, "version_minor": 0 }, "text/plain": [ "Checkbox(value=False, description='Check box')" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "095991210fae4088aab874ad9799af83", "version_major": 2, "version_minor": 0 }, "text/plain": [ "Valid(value=True, description='Is it valid?')" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "52b161a49b8f4560bdf2d91bc876d154", "version_major": 2, "version_minor": 0 }, "text/plain": [ "Valid(value=False, description='Is it valid?', readout='')" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "ba = widgets.ToggleButton(value=False, description='Toggle!', tooltip=\"click to change\")\n", "bb = widgets.Checkbox(value=False, description=\"Check box\")\n", "bc = widgets.Valid(value=True, description='Is it valid?')\n", "bd = widgets.Valid(value=False, description='Is it valid?', readout=\"\")\n", "\n", "display(ba, bb, bc, bd)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "It is also common to select an option from a set of defined options." ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [ { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "5f4d7ff45a734cdb8a46987f9fa6a2c8", "version_major": 2, "version_minor": 0 }, "text/plain": [ "Dropdown(description='Pick one:', index=2, options=(2, 4, 6, 8), value=6)" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "5c6170545b184b8092323a89e130bad8", "version_major": 2, "version_minor": 0 }, "text/plain": [ "Dropdown(description='Pick one:', index=2, options=(('Cat', 1), ('Dog', 2), ('Hen', 3)), value=3)" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "51787e044fd04c1fbe7e113befc1325e", "version_major": 2, "version_minor": 0 }, "text/plain": [ "RadioButtons(options=('Cat', 'Dog', 'Hen'), value='Cat')" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "8cb88368f9b04adc8bd669d3d6b16823", "version_major": 2, "version_minor": 0 }, "text/plain": [ "ToggleButtons(options=('Cat', 'Dog', 'Hen'), value='Cat')" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "118a9694c2de4a19afd9b755dcd97967", "version_major": 2, "version_minor": 0 }, "text/plain": [ "Select(options=('Select one', 'Cat', 'Dog', 'Hen'), value='Select one')" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "242a0d34f7fa471e89bab17e15be961e", "version_major": 2, "version_minor": 0 }, "text/plain": [ "SelectMultiple(options=('Select many', 'Cat', 'Dog', 'Hen'), value=())" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "pa = widgets.Dropdown(options=[2, 4, 6, 8], value=6, description='Pick one:')\n", "pb = widgets.Dropdown(options=[('Cat', 1), ('Dog', 2), ('Hen', 3)], value=3, description='Pick one:')\n", "pc = widgets.RadioButtons(options=['Cat', 'Dog', 'Hen'])\n", "pd = widgets.ToggleButtons(options=['Cat', 'Dog', 'Hen'])\n", "pe = widgets.Select(options=['Select one', 'Cat', 'Dog', 'Hen'], value='Select one')\n", "pf = widgets.SelectMultiple(options=['Select many', 'Cat', 'Dog', 'Hen'])\n", "\n", "display(pa, pb, pc, pd, pe, pf)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "It is also often necessicary to input text." ] }, { "cell_type": "code", "execution_count": 16, "metadata": {}, "outputs": [ { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "34af2e3921eb441199c1f50aafe22825", "version_major": 2, "version_minor": 0 }, "text/plain": [ "Text(value='Hello!')" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "4d3ac7c783cd4a73bbe6ad594dcdb4be", "version_major": 2, "version_minor": 0 }, "text/plain": [ "Textarea(value='Hello! Type something longer here!')" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "ta = widgets.Text(value='Hello!')\n", "tb = widgets.Textarea(value='Hello! Type something longer here!')\n", "\n", "display(ta, tb)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "There are several more powerful widgets that you might have a certain use for, such as the `HTML`, `HTML Math`, `Image`, `Output`, `Play`, or `File Upload` widgets which you can check out [here](https://ipywidgets.readthedocs.io/en/latest/examples/Widget%20List.html#HTML). Two that might be useful for geospatial data are the `Date Picker` and `Color Picker` widgets, which are shown below." ] }, { "cell_type": "code", "execution_count": 17, "metadata": {}, "outputs": [ { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "034cd6666f334da1a1f8a5102577abb7", "version_major": 2, "version_minor": 0 }, "text/plain": [ "DatePicker(value=None)" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "dpa = widgets.DatePicker() # warning, does not work in the Safari browser\n", "\n", "display(dpa)" ] }, { "cell_type": "code", "execution_count": 18, "metadata": {}, "outputs": [ { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "5c7633afd3f54a3ea60fb0b8185ac1de", "version_major": 2, "version_minor": 0 }, "text/plain": [ "ColorPicker(value='orange')" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "cpa = widgets.ColorPicker(value='orange') \n", "\n", "display(cpa)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "### Handling simple widget events" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In this section some very basic widget events will be demonstrated, showing some of the ways you can use data from widgets." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Generally there are two techniques that you can use to gather infirmation from widgets:\n", "1. Allow choices to be made freely, but save values when an action is taken (such as a `submit` button is pressed)\n", "2. Constantly update values as they are changed" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Record values on submit" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This shows a simple example of a way to have something happen if you click a button." ] }, { "cell_type": "code", "execution_count": 19, "metadata": {}, "outputs": [ { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "c4f670b810864b22a16b53a7b843254a", "version_major": 2, "version_minor": 0 }, "text/plain": [ "FloatSlider(value=3.0, max=9.0, step=1.0)" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "46470c7b05be4277b0d31e86ce374e2e", "version_major": 2, "version_minor": 0 }, "text/plain": [ "Button(description='Click to submit', style=ButtonStyle(button_color='orange'))" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "5185e6e507ab4bb79d9041a7535bc625", "version_major": 2, "version_minor": 0 }, "text/plain": [ "Output()" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "seva = widgets.FloatSlider(value=3, min=0, max=9, step=1)\n", "sevb = widgets.Button(description='Click to submit', style=widgets.ButtonStyle(button_color='orange'))\n", "soutwidget = widgets.Output()\n", "\n", "def run_on_button_clicked(button):\n", " print(\"You clicked: slider: \", str(seva.value))\n", "\n", "sevb.on_click(run_on_button_clicked)\n", "display(seva, sevb, soutwidget)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This example is slightly more complex, but works similarly to the example above." ] }, { "cell_type": "code", "execution_count": 20, "metadata": {}, "outputs": [ { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "adcd75ed38424b6c8d167ea3ace72f9a", "version_major": 2, "version_minor": 0 }, "text/plain": [ "Output()" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "d3e0d0ac83ed452584a586e733f1c2ee", "version_major": 2, "version_minor": 0 }, "text/plain": [ "FloatSlider(value=3.0, max=9.0, step=1.0)" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "de99efa8998f468eaf6aad8ac75bd5ae", "version_major": 2, "version_minor": 0 }, "text/plain": [ "ToggleButtons(options=('Cat', 'Dog', 'Hen'), value='Cat')" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "58507425406d49af82f5cf70fa38716d", "version_major": 2, "version_minor": 0 }, "text/plain": [ "Text(value='')" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "f6f1a0ef2c5f4e1bade68de1623f616f", "version_major": 2, "version_minor": 0 }, "text/plain": [ "Button(description='Click to submit', style=ButtonStyle(button_color='orange'))" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "004c8ef0eeb54819a989fbcc83103c6f", "version_major": 2, "version_minor": 0 }, "text/plain": [ "Button(description='Click to clear', style=ButtonStyle(button_color='lightblue'))" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "6a4ced1a4dde4a2ba6bebded37ae7844", "version_major": 2, "version_minor": 0 }, "text/plain": [ "Output(layout=Layout(border='1px solid black'))" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "eva = widgets.FloatSlider(value=3, min=0, max=9, step=1)\n", "evb = widgets.ToggleButtons(options=['Cat', 'Dog', 'Hen'])\n", "evc = widgets.Text()\n", "evd = widgets.Button(description='Click to submit', style=widgets.ButtonStyle(button_color='orange'))\n", "eve = widgets.Button(description='Click to clear', style=widgets.ButtonStyle(button_color='lightblue'))\n", "\n", "outplot = widgets.Output()\n", "outwidget = widgets.Output(layout={'border': '1px solid black'})\n", "\n", "with outplot:\n", " plt.figure(figsize=(2, 2))\n", " plt.scatter((0, 1, 0.5), (0, 0, 1), color = \"red\")\n", " plt.show()\n", "\n", "def run_on_button_clicked(button):\n", " with outwidget:\n", " outwidget.clear_output(wait=False)\n", " print(\"You clicked:\")\n", " print(\"\\tslider: \", str(eva.value))\n", " print(\"\\ttoggle: \", str(evb.value))\n", " print(\"\\ttext: \", str(evc.value))\n", " with outplot:\n", " outplot.clear_output()\n", " plt.figure(figsize=(2, 2))\n", " plt.scatter((0, 1, 0.5), (0, 0, 1), color = \"blue\")\n", " plt.show()\n", " \n", "def clear_out(button):\n", " outwidget.clear_output()\n", " with outplot:\n", " outplot.clear_output()\n", " plt.figure(figsize=(2, 2))\n", " plt.scatter((0, 1, 0.5), (0, 0, 1), color = \"red\")\n", " plt.show()\n", "\n", "evd.on_click(run_on_button_clicked)\n", "eve.on_click(clear_out)\n", "\n", "\n", "display(outplot, eva, evb, evc, evd, eve, outwidget)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Constantly update values" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In each of the above examples, nothing happened unless you clicked a button. This is useful for forms and inputs that require some form of error checking before incorporating into your program. However, there is another way to get input that is good for instant feedback.\n", "\n", "`%matplotlib notebook` is a special function that allows the figure to be updated when notebook values change." ] }, { "cell_type": "code", "execution_count": 21, "metadata": {}, "outputs": [ { "data": { "application/javascript": [ "/* Put everything inside the global mpl namespace */\n", "window.mpl = {};\n", "\n", "\n", "mpl.get_websocket_type = function() {\n", " if (typeof(WebSocket) !== 'undefined') {\n", " return WebSocket;\n", " } else if (typeof(MozWebSocket) !== 'undefined') {\n", " return MozWebSocket;\n", " } else {\n", " alert('Your browser does not have WebSocket support. ' +\n", " 'Please try Chrome, Safari or Firefox ≥ 6. ' +\n", " 'Firefox 4 and 5 are also supported but you ' +\n", " 'have to enable WebSockets in about:config.');\n", " };\n", "}\n", "\n", "mpl.figure = function(figure_id, websocket, ondownload, parent_element) {\n", " this.id = figure_id;\n", "\n", " this.ws = websocket;\n", "\n", " this.supports_binary = (this.ws.binaryType != undefined);\n", "\n", " if (!this.supports_binary) {\n", " var warnings = document.getElementById(\"mpl-warnings\");\n", " if (warnings) {\n", " warnings.style.display = 'block';\n", " warnings.textContent = (\n", " \"This browser does not support binary websocket messages. \" +\n", " \"Performance may be slow.\");\n", " }\n", " }\n", "\n", " this.imageObj = new Image();\n", "\n", " this.context = undefined;\n", " this.message = undefined;\n", " this.canvas = undefined;\n", " this.rubberband_canvas = undefined;\n", " this.rubberband_context = undefined;\n", " this.format_dropdown = undefined;\n", "\n", " this.image_mode = 'full';\n", "\n", " this.root = $('
');\n", " this._root_extra_style(this.root)\n", " this.root.attr('style', 'display: inline-block');\n", "\n", " $(parent_element).append(this.root);\n", "\n", " this._init_header(this);\n", " this._init_canvas(this);\n", " this._init_toolbar(this);\n", "\n", " var fig = this;\n", "\n", " this.waiting = false;\n", "\n", " this.ws.onopen = function () {\n", " fig.send_message(\"supports_binary\", {value: fig.supports_binary});\n", " fig.send_message(\"send_image_mode\", {});\n", " if (mpl.ratio != 1) {\n", " fig.send_message(\"set_dpi_ratio\", {'dpi_ratio': mpl.ratio});\n", " }\n", " fig.send_message(\"refresh\", {});\n", " }\n", "\n", " this.imageObj.onload = function() {\n", " if (fig.image_mode == 'full') {\n", " // Full images could contain transparency (where diff images\n", " // almost always do), so we need to clear the canvas so that\n", " // there is no ghosting.\n", " fig.context.clearRect(0, 0, fig.canvas.width, fig.canvas.height);\n", " }\n", " fig.context.drawImage(fig.imageObj, 0, 0);\n", " };\n", "\n", " this.imageObj.onunload = function() {\n", " fig.ws.close();\n", " }\n", "\n", " this.ws.onmessage = this._make_on_message_function(this);\n", "\n", " this.ondownload = ondownload;\n", "}\n", "\n", "mpl.figure.prototype._init_header = function() {\n", " var titlebar = $(\n", " '
');\n", " var titletext = $(\n", " '
');\n", " titlebar.append(titletext)\n", " this.root.append(titlebar);\n", " this.header = titletext[0];\n", "}\n", "\n", "\n", "\n", "mpl.figure.prototype._canvas_extra_style = function(canvas_div) {\n", "\n", "}\n", "\n", "\n", "mpl.figure.prototype._root_extra_style = function(canvas_div) {\n", "\n", "}\n", "\n", "mpl.figure.prototype._init_canvas = function() {\n", " var fig = this;\n", "\n", " var canvas_div = $('
');\n", "\n", " canvas_div.attr('style', 'position: relative; clear: both; outline: 0');\n", "\n", " function canvas_keyboard_event(event) {\n", " return fig.key_event(event, event['data']);\n", " }\n", "\n", " canvas_div.keydown('key_press', canvas_keyboard_event);\n", " canvas_div.keyup('key_release', canvas_keyboard_event);\n", " this.canvas_div = canvas_div\n", " this._canvas_extra_style(canvas_div)\n", " this.root.append(canvas_div);\n", "\n", " var canvas = $('');\n", " canvas.addClass('mpl-canvas');\n", " canvas.attr('style', \"left: 0; top: 0; z-index: 0; outline: 0\")\n", "\n", " this.canvas = canvas[0];\n", " this.context = canvas[0].getContext(\"2d\");\n", "\n", " var backingStore = this.context.backingStorePixelRatio ||\n", "\tthis.context.webkitBackingStorePixelRatio ||\n", "\tthis.context.mozBackingStorePixelRatio ||\n", "\tthis.context.msBackingStorePixelRatio ||\n", "\tthis.context.oBackingStorePixelRatio ||\n", "\tthis.context.backingStorePixelRatio || 1;\n", "\n", " mpl.ratio = (window.devicePixelRatio || 1) / backingStore;\n", "\n", " var rubberband = $('');\n", " rubberband.attr('style', \"position: absolute; left: 0; top: 0; z-index: 1;\")\n", "\n", " var pass_mouse_events = true;\n", "\n", " canvas_div.resizable({\n", " start: function(event, ui) {\n", " pass_mouse_events = false;\n", " },\n", " resize: function(event, ui) {\n", " fig.request_resize(ui.size.width, ui.size.height);\n", " },\n", " stop: function(event, ui) {\n", " pass_mouse_events = true;\n", " fig.request_resize(ui.size.width, ui.size.height);\n", " },\n", " });\n", "\n", " function mouse_event_fn(event) {\n", " if (pass_mouse_events)\n", " return fig.mouse_event(event, event['data']);\n", " }\n", "\n", " rubberband.mousedown('button_press', mouse_event_fn);\n", " rubberband.mouseup('button_release', mouse_event_fn);\n", " // Throttle sequential mouse events to 1 every 20ms.\n", " rubberband.mousemove('motion_notify', mouse_event_fn);\n", "\n", " rubberband.mouseenter('figure_enter', mouse_event_fn);\n", " rubberband.mouseleave('figure_leave', mouse_event_fn);\n", "\n", " canvas_div.on(\"wheel\", function (event) {\n", " event = event.originalEvent;\n", " event['data'] = 'scroll'\n", " if (event.deltaY < 0) {\n", " event.step = 1;\n", " } else {\n", " event.step = -1;\n", " }\n", " mouse_event_fn(event);\n", " });\n", "\n", " canvas_div.append(canvas);\n", " canvas_div.append(rubberband);\n", "\n", " this.rubberband = rubberband;\n", " this.rubberband_canvas = rubberband[0];\n", " this.rubberband_context = rubberband[0].getContext(\"2d\");\n", " this.rubberband_context.strokeStyle = \"#000000\";\n", "\n", " this._resize_canvas = function(width, height) {\n", " // Keep the size of the canvas, canvas container, and rubber band\n", " // canvas in synch.\n", " canvas_div.css('width', width)\n", " canvas_div.css('height', height)\n", "\n", " canvas.attr('width', width * mpl.ratio);\n", " canvas.attr('height', height * mpl.ratio);\n", " canvas.attr('style', 'width: ' + width + 'px; height: ' + height + 'px;');\n", "\n", " rubberband.attr('width', width);\n", " rubberband.attr('height', height);\n", " }\n", "\n", " // Set the figure to an initial 600x600px, this will subsequently be updated\n", " // upon first draw.\n", " this._resize_canvas(600, 600);\n", "\n", " // Disable right mouse context menu.\n", " $(this.rubberband_canvas).bind(\"contextmenu\",function(e){\n", " return false;\n", " });\n", "\n", " function set_focus () {\n", " canvas.focus();\n", " canvas_div.focus();\n", " }\n", "\n", " window.setTimeout(set_focus, 100);\n", "}\n", "\n", "mpl.figure.prototype._init_toolbar = function() {\n", " var fig = this;\n", "\n", " var nav_element = $('
');\n", " nav_element.attr('style', 'width: 100%');\n", " this.root.append(nav_element);\n", "\n", " // Define a callback function for later on.\n", " function toolbar_event(event) {\n", " return fig.toolbar_button_onclick(event['data']);\n", " }\n", " function toolbar_mouse_event(event) {\n", " return fig.toolbar_button_onmouseover(event['data']);\n", " }\n", "\n", " for(var toolbar_ind in mpl.toolbar_items) {\n", " var name = mpl.toolbar_items[toolbar_ind][0];\n", " var tooltip = mpl.toolbar_items[toolbar_ind][1];\n", " var image = mpl.toolbar_items[toolbar_ind][2];\n", " var method_name = mpl.toolbar_items[toolbar_ind][3];\n", "\n", " if (!name) {\n", " // put a spacer in here.\n", " continue;\n", " }\n", " var button = $('