| 1 |
{ |
| 2 |
"cells": [ |
| 3 |
{ |
| 4 |
"cell_type": "markdown", |
| 5 |
"metadata": {}, |
| 6 |
"source": [ |
| 7 |
"# Building interactive plots using `bqplot` and `ipywidgets`" |
| 8 |
] |
| 9 |
}, |
| 10 |
{ |
| 11 |
"cell_type": "markdown", |
| 12 |
"metadata": {}, |
| 13 |
"source": [ |
| 14 |
"* `bqplot` is built on top of the `ipywidgets` framework\n", |
| 15 |
"* `ipwidgets` and `bqplot` widgets can be seamlessly integrated to build interactive plots\n", |
| 16 |
"* `bqplot` figure widgets can be stacked with UI controls available in `ipywidgets` by using `Layout` classes (Box, HBox, VBox) in `ipywidgets`\n", |
| 17 |
"(Note that *only* `Figure` objects (not `Mark` objects) inherit from `DOMWidget` class and can be combined with other widgets from `ipywidgets`)\n", |
| 18 |
"* Trait attributes of widgets can be linked using callbacks. Callbacks should be registered using the `observe` method\n", |
| 19 |
"\n", |
| 20 |
"Please follow these links for detailed documentation on:\n", |
| 21 |
"1. [Layout and Styling of Jupyter Widgets](https://ipywidgets.readthedocs.io/en/stable/examples/Widget%20Styling.html)\n", |
| 22 |
"* [Linking Widgets](https://ipywidgets.readthedocs.io/en/stable/examples/Widget%20Events.html)\n", |
| 23 |
"\n", |
| 24 |
"<br>Let's look at examples of linking plots with UI controls" |
| 25 |
] |
| 26 |
}, |
| 27 |
{ |
| 28 |
"cell_type": "code", |
| 29 |
"execution_count": null, |
| 30 |
"metadata": {}, |
| 31 |
"outputs": [], |
| 32 |
"source": [ |
| 33 |
"import numpy as np" |
| 34 |
] |
| 35 |
}, |
| 36 |
{ |
| 37 |
"cell_type": "code", |
| 38 |
"execution_count": null, |
| 39 |
"metadata": {}, |
| 40 |
"outputs": [], |
| 41 |
"source": [ |
| 42 |
"import ipywidgets as widgets\n", |
| 43 |
"import bqplot.pyplot as plt" |
| 44 |
] |
| 45 |
}, |
| 46 |
{ |
| 47 |
"cell_type": "markdown", |
| 48 |
"metadata": {}, |
| 49 |
"source": [ |
| 50 |
"Update the plot on a button click" |
| 51 |
] |
| 52 |
}, |
| 53 |
{ |
| 54 |
"cell_type": "code", |
| 55 |
"execution_count": null, |
| 56 |
"metadata": {}, |
| 57 |
"outputs": [], |
| 58 |
"source": [ |
| 59 |
"y = np.random.randn(100).cumsum() # simple random walk\n", |
| 60 |
"\n", |
| 61 |
"# create a button\n", |
| 62 |
"update_btn = widgets.Button(description='Update', button_style='success')\n", |
| 63 |
"\n", |
| 64 |
"# create a figure widget\n", |
| 65 |
"fig1 = plt.figure(animation_duration=750)\n", |
| 66 |
"line = plt.plot(y)\n", |
| 67 |
"\n", |
| 68 |
"# define an on_click function\n", |
| 69 |
"def on_btn_click(btn):\n", |
| 70 |
" # update the y attribute of line mark\n", |
| 71 |
" line.y = np.random.randn(100).cumsum() # another random walk\n", |
| 72 |
"\n", |
| 73 |
"# register the on_click function\n", |
| 74 |
"update_btn.on_click(on_btn_click)\n", |
| 75 |
" \n", |
| 76 |
"# stack button and figure using VBox\n", |
| 77 |
"widgets.VBox([fig1, update_btn])" |
| 78 |
] |
| 79 |
}, |
| 80 |
{ |
| 81 |
"cell_type": "markdown", |
| 82 |
"metadata": {}, |
| 83 |
"source": [ |
| 84 |
"Let's look at an example where we link a plot to a dropdown menu" |
| 85 |
] |
| 86 |
}, |
| 87 |
{ |
| 88 |
"cell_type": "code", |
| 89 |
"execution_count": null, |
| 90 |
"metadata": {}, |
| 91 |
"outputs": [], |
| 92 |
"source": [ |
| 93 |
"import pandas as pd\n", |
| 94 |
"\n", |
| 95 |
"# create a dummy time series for 5 dummy stock tickers\n", |
| 96 |
"dates = pd.date_range(start='20180101', end='20181231')\n", |
| 97 |
"n = len(dates)\n", |
| 98 |
"tickers = list('ABCDE')\n", |
| 99 |
"prices = pd.DataFrame(np.random.randn(n, 5).cumsum(axis=0), columns=tickers)" |
| 100 |
] |
| 101 |
}, |
| 102 |
{ |
| 103 |
"cell_type": "code", |
| 104 |
"execution_count": null, |
| 105 |
"metadata": {}, |
| 106 |
"outputs": [], |
| 107 |
"source": [ |
| 108 |
"# create a dropdown menu for tickers\n", |
| 109 |
"dropdown = widgets.Dropdown(description='Ticker', options=tickers)\n", |
| 110 |
"\n", |
| 111 |
"# create figure for plotting time series\n", |
| 112 |
"current_ticker = dropdown.value\n", |
| 113 |
"fig_title_tmpl = '\"{}\" Time Series' # string template for title of the figure \n", |
| 114 |
"fig2 = plt.figure(title=fig_title_tmpl.format(current_ticker))\n", |
| 115 |
"fig2.layout.width = '900px'\n", |
| 116 |
"time_series = plt.plot(dates, prices[current_ticker])\n", |
| 117 |
"plt.xlabel('Date')\n", |
| 118 |
"plt.ylabel('Price')\n", |
| 119 |
"\n", |
| 120 |
"# 1. create a callback which updates the plot when dropdown item is selected\n", |
| 121 |
"def update_plot(*args):\n", |
| 122 |
" selected_ticker = dropdown.value\n", |
| 123 |
" \n", |
| 124 |
" # update the y attribute of the mark by selecting \n", |
| 125 |
" # the column from the price data frame\n", |
| 126 |
" time_series.y = prices[selected_ticker]\n", |
| 127 |
" \n", |
| 128 |
" # update the title of the figure\n", |
| 129 |
" fig2.title = fig_title_tmpl.format(selected_ticker)\n", |
| 130 |
"\n", |
| 131 |
"# 2. register the callback by using the 'observe' method\n", |
| 132 |
"dropdown.observe(update_plot, 'value')\n", |
| 133 |
"\n", |
| 134 |
"# stack the dropdown and fig widgets using VBox\n", |
| 135 |
"widgets.VBox([dropdown, fig2])" |
| 136 |
] |
| 137 |
}, |
| 138 |
{ |
| 139 |
"cell_type": "markdown", |
| 140 |
"metadata": {}, |
| 141 |
"source": [ |
| 142 |
"Let's now create a scatter plot where we select X and Y data from the two dropdown menus" |
| 143 |
] |
| 144 |
}, |
| 145 |
{ |
| 146 |
"cell_type": "code", |
| 147 |
"execution_count": null, |
| 148 |
"metadata": {}, |
| 149 |
"outputs": [], |
| 150 |
"source": [ |
| 151 |
"# create two dropdown menus for X and Y attributes of scatter\n", |
| 152 |
"x_dropdown = widgets.Dropdown(description='X', options=tickers, value='A')\n", |
| 153 |
"y_dropdown = widgets.Dropdown(description='Y', options=tickers, value='B')\n", |
| 154 |
"\n", |
| 155 |
"# create figure for plotting the scatter\n", |
| 156 |
"x_ticker = x_dropdown.value\n", |
| 157 |
"y_ticker = y_dropdown.value\n", |
| 158 |
"\n", |
| 159 |
"# set up fig_margin to allow space to display color bar\n", |
| 160 |
"fig_margin = dict(top=20, bottom=40, left=60, right=80)\n", |
| 161 |
"fig3 = plt.figure(animation_duration=1000, fig_margin=fig_margin)\n", |
| 162 |
"\n", |
| 163 |
"# custom axis options for color data\n", |
| 164 |
"axes_options = {'color': {'tick_format': '%m/%y', \n", |
| 165 |
" 'side': 'right',\n", |
| 166 |
" 'num_ticks': 5}}\n", |
| 167 |
"scatter = plt.scatter(x=prices[x_ticker], \n", |
| 168 |
" y=prices[y_ticker],\n", |
| 169 |
" color=dates, # represent chronology using color scale\n", |
| 170 |
" stroke='black',\n", |
| 171 |
" colors=['red'],\n", |
| 172 |
" default_size=32,\n", |
| 173 |
" axes_options=axes_options)\n", |
| 174 |
"plt.xlabel(x_ticker)\n", |
| 175 |
"plt.ylabel(y_ticker)\n", |
| 176 |
"\n", |
| 177 |
"# 1. create a callback which updates the plot when dropdown item is selected\n", |
| 178 |
"def update_scatter(*args):\n", |
| 179 |
" x_ticker = x_dropdown.value\n", |
| 180 |
" y_ticker = y_dropdown.value\n", |
| 181 |
" \n", |
| 182 |
" # update the x and y attributes of the mark by selecting\n", |
| 183 |
" # the column from the price data frame\n", |
| 184 |
" with scatter.hold_sync():\n", |
| 185 |
" scatter.x = prices[x_ticker]\n", |
| 186 |
" scatter.y = prices[y_ticker]\n", |
| 187 |
" \n", |
| 188 |
" # update the title of the figure\n", |
| 189 |
" plt.xlabel(x_ticker)\n", |
| 190 |
" plt.ylabel(y_ticker)\n", |
| 191 |
"\n", |
| 192 |
"# 2. register the callback by using the 'observe' method\n", |
| 193 |
"x_dropdown.observe(update_scatter, 'value')\n", |
| 194 |
"y_dropdown.observe(update_scatter, 'value')\n", |
| 195 |
"\n", |
| 196 |
"# stack the dropdown and fig widgets using VBox\n", |
| 197 |
"widgets.VBox([widgets.HBox([x_dropdown, y_dropdown]), fig3])" |
| 198 |
] |
| 199 |
}, |
| 200 |
{ |
| 201 |
"cell_type": "markdown", |
| 202 |
"metadata": {}, |
| 203 |
"source": [ |
| 204 |
"In the example below, we'll look at plots of trigonometic functions" |
| 205 |
] |
| 206 |
}, |
| 207 |
{ |
| 208 |
"cell_type": "code", |
| 209 |
"execution_count": null, |
| 210 |
"metadata": {}, |
| 211 |
"outputs": [], |
| 212 |
"source": [ |
| 213 |
"funcs = dict(sin=np.sin, cos=np.cos, tan=np.tan, sinh=np.sinh, tanh=np.tanh)\n", |
| 214 |
"dropdown = widgets.Dropdown(options=funcs, description='Function')\n", |
| 215 |
"\n", |
| 216 |
"fig = plt.figure(title='sin(x)', animation_duration=1000)\n", |
| 217 |
"\n", |
| 218 |
"# create x and y data attributes for the line chart\n", |
| 219 |
"x = np.arange(-10, 10, .1)\n", |
| 220 |
"y = np.sin(x)\n", |
| 221 |
"\n", |
| 222 |
"line = plt.plot(x, y ,'m')\n", |
| 223 |
"\n", |
| 224 |
"def update_line(*args):\n", |
| 225 |
" f = dropdown.value\n", |
| 226 |
" fig.title = f'{f.__name__}(x)'\n", |
| 227 |
" line.y = f(line.x)\n", |
| 228 |
" \n", |
| 229 |
"dropdown.observe(update_line, 'value')\n", |
| 230 |
"\n", |
| 231 |
"widgets.VBox([dropdown, fig])" |
| 232 |
] |
| 233 |
} |
| 234 |
], |
| 235 |
"metadata": { |
| 236 |
"kernelspec": { |
| 237 |
"display_name": "Python 3", |
| 238 |
"language": "python", |
| 239 |
"name": "python3" |
| 240 |
}, |
| 241 |
"language_info": { |
| 242 |
"codemirror_mode": { |
| 243 |
"name": "ipython", |
| 244 |
"version": 3 |
| 245 |
}, |
| 246 |
"file_extension": ".py", |
| 247 |
"mimetype": "text/x-python", |
| 248 |
"name": "python", |
| 249 |
"nbconvert_exporter": "python", |
| 250 |
"pygments_lexer": "ipython3", |
| 251 |
"version": "3.8.2" |
| 252 |
} |
| 253 |
}, |
| 254 |
"nbformat": 4, |
| 255 |
"nbformat_minor": 1 |
| 256 |
} |