Debian Codegraph @

bqplot/examples/Introduction.ipynb

raw
1 {
2 "cells": [
3 {
4 "cell_type": "markdown",
5 "metadata": {},
6 "source": [
7 "# bqplot"
8 ]
9 },
10 {
11 "cell_type": "markdown",
12 "metadata": {},
13 "source": [
14 "This notebook is meant to guide you through the first stages of using the `bqplot` visualization library. `bqplot` is a Grammar of Graphics based interactive visualization library for the Jupyter notebook where every single component of a plot is an interactive iPython widget. What this means is that even after a plot is drawn, you can change almost any aspect of it. This makes the creation of advanced Graphical User Interfaces attainable through just a few simple lines of Python code."
15 ]
16 },
17 {
18 "cell_type": "code",
19 "execution_count": null,
20 "metadata": {},
21 "outputs": [],
22 "source": [
23 "# Let's begin by importing some libraries we'll need\n",
24 "import numpy as np"
25 ]
26 },
27 {
28 "cell_type": "code",
29 "execution_count": null,
30 "metadata": {},
31 "outputs": [],
32 "source": [
33 "# And creating some random data\n",
34 "size = 100\n",
35 "np.random.seed(0)\n",
36 "x_data = np.arange(size)\n",
37 "y_data = np.cumsum(np.random.randn(size) * 100.0)"
38 ]
39 },
40 {
41 "cell_type": "markdown",
42 "metadata": {},
43 "source": [
44 "## Your First Plot"
45 ]
46 },
47 {
48 "cell_type": "markdown",
49 "metadata": {},
50 "source": [
51 "Let's start by creating a simple Line chart. `bqplot` has two different APIs, the first one is a `matplotlib` inspired simple API called `pyplot`. So let's import that."
52 ]
53 },
54 {
55 "cell_type": "code",
56 "execution_count": null,
57 "metadata": {},
58 "outputs": [],
59 "source": [
60 "from bqplot import pyplot as plt"
61 ]
62 },
63 {
64 "cell_type": "markdown",
65 "metadata": {},
66 "source": [
67 "Let's plot `y_data` against `x_data`, and then `show` the plot."
68 ]
69 },
70 {
71 "cell_type": "code",
72 "execution_count": null,
73 "metadata": {},
74 "outputs": [],
75 "source": [
76 "plt.figure(title='My First Plot')\n",
77 "plt.plot(x_data, y_data)\n",
78 "plt.show()"
79 ]
80 },
81 {
82 "cell_type": "markdown",
83 "metadata": {},
84 "source": [
85 "Use the buttons above to Pan (or Zoom), Reset or save the Figure."
86 ]
87 },
88 {
89 "cell_type": "markdown",
90 "metadata": {},
91 "source": [
92 "## Using `bqplot`'s interactive elements"
93 ]
94 },
95 {
96 "cell_type": "markdown",
97 "metadata": {},
98 "source": [
99 "Now, let's try creating a new plot. First, we create a brand new `Figure`. The `Figure` is the final element of any plot that is eventually displayed. You can think of it as a Canvas on which we put all of our other plots."
100 ]
101 },
102 {
103 "cell_type": "code",
104 "execution_count": null,
105 "metadata": {},
106 "outputs": [],
107 "source": [
108 "# Creating a new Figure and setting it's title\n",
109 "plt.figure(title='My Second Chart')"
110 ]
111 },
112 {
113 "cell_type": "code",
114 "execution_count": null,
115 "metadata": {},
116 "outputs": [],
117 "source": [
118 "# Let's assign the scatter plot to a variable\n",
119 "scatter_plot = plt.scatter(x_data, y_data)"
120 ]
121 },
122 {
123 "cell_type": "code",
124 "execution_count": null,
125 "metadata": {
126 "scrolled": false
127 },
128 "outputs": [],
129 "source": [
130 "# Let's show the plot\n",
131 "plt.show()"
132 ]
133 },
134 {
135 "cell_type": "markdown",
136 "metadata": {},
137 "source": [
138 "Since both the x and the y attributes of a bqplot chart are interactive widgets, we can change them. So, let's \n",
139 "change the y attribute of the chart."
140 ]
141 },
142 {
143 "cell_type": "code",
144 "execution_count": null,
145 "metadata": {},
146 "outputs": [],
147 "source": [
148 "scatter_plot.y = np.cumsum(np.random.randn(size) * 100.0)"
149 ]
150 },
151 {
152 "cell_type": "markdown",
153 "metadata": {},
154 "source": [
155 "Re-run the above cell a few times, the same plot should update every time. But, that's not the only thing that can be changed once a plot has been rendered. Let's try changing some of the other attributes."
156 ]
157 },
158 {
159 "cell_type": "code",
160 "execution_count": null,
161 "metadata": {},
162 "outputs": [],
163 "source": [
164 "# Say, the color\n",
165 "scatter_plot.colors = ['Red']"
166 ]
167 },
168 {
169 "cell_type": "code",
170 "execution_count": null,
171 "metadata": {},
172 "outputs": [],
173 "source": [
174 "# Or, the marker style\n",
175 "scatter_plot.marker = 'diamond'"
176 ]
177 },
178 {
179 "cell_type": "markdown",
180 "metadata": {},
181 "source": [
182 "It's important to remember that an interactive widget means that the `JavaScript` and the `Python` communicate. So, the plot can be changed through a single line of python code, or a piece of python code can be triggered by a change in the plot. Let's go through a simple example. Say we have a function `foo`:"
183 ]
184 },
185 {
186 "cell_type": "code",
187 "execution_count": null,
188 "metadata": {},
189 "outputs": [],
190 "source": [
191 "def foo(change):\n",
192 " print('This is a trait change. Foo was called by the fact that we moved the Scatter')\n",
193 " print('In fact, the Scatter plot sent us all the new data: ')\n",
194 " print('To access the data, try modifying the function and printing the data variable')"
195 ]
196 },
197 {
198 "cell_type": "markdown",
199 "metadata": {},
200 "source": [
201 "We can call `foo` every time any attribute of our scatter is changed. Say, the `y` values:"
202 ]
203 },
204 {
205 "cell_type": "code",
206 "execution_count": null,
207 "metadata": {},
208 "outputs": [],
209 "source": [
210 "# First, we hook up our function `foo` to the colors attribute (or Trait) of the scatter plot\n",
211 "scatter_plot.observe(foo, 'y')"
212 ]
213 },
214 {
215 "cell_type": "markdown",
216 "metadata": {},
217 "source": [
218 "To allow the points in the `Scatter` to be moved interactively, we set the `enable_move` attribute to `True`"
219 ]
220 },
221 {
222 "cell_type": "code",
223 "execution_count": null,
224 "metadata": {},
225 "outputs": [],
226 "source": [
227 "scatter_plot.enable_move = True"
228 ]
229 },
230 {
231 "cell_type": "markdown",
232 "metadata": {},
233 "source": [
234 "Go ahead, head over to the chart and move any point in some way. This move (which happens on the `JavaScript` side should trigger our `Python` function `foo`."
235 ]
236 },
237 {
238 "cell_type": "markdown",
239 "metadata": {
240 "collapsed": true
241 },
242 "source": [
243 "## Understanding how bqplot uses the Grammar of Graphics paradigm"
244 ]
245 },
246 {
247 "cell_type": "markdown",
248 "metadata": {},
249 "source": [
250 "`bqplot` has two different APIs. One is the matplotlib inspired `pyplot` which we used above (you can think of it as similar to `qplot` in `ggplot2`). The other one, the verbose API, is meant to expose every element of a plot individually, so that their attriutes can be controlled in an atomic way. In order to truly use `bqplot` to build complex and feature-rich GUIs, it pays to understand the underlying theory that is used to create a plot."
251 ]
252 },
253 {
254 "cell_type": "markdown",
255 "metadata": {},
256 "source": [
257 "To understand this verbose API, it helps to revisit what exactly the components of a plot are. The first thing we need is a `Scale`."
258 ]
259 },
260 {
261 "cell_type": "markdown",
262 "metadata": {},
263 "source": [
264 "**A `Scale` is a mapping from (function that converts) data coordinates to figure coordinates.** What this means is that, a `Scale` takes a set of values in any arbitrary unit (say number of people, or $, or litres) and converts it to pixels (or colors for a `ColorScale`)."
265 ]
266 },
267 {
268 "cell_type": "code",
269 "execution_count": null,
270 "metadata": {},
271 "outputs": [],
272 "source": [
273 "# First, we import the scales\n",
274 "from bqplot import LinearScale"
275 ]
276 },
277 {
278 "cell_type": "code",
279 "execution_count": null,
280 "metadata": {},
281 "outputs": [],
282 "source": [
283 "# Let's create a scale for the x attribute, and a scale for the y attribute\n",
284 "x_sc = LinearScale()\n",
285 "y_sc = LinearScale()"
286 ]
287 },
288 {
289 "cell_type": "markdown",
290 "metadata": {},
291 "source": [
292 "Now, we need to create the actual `Mark` that will visually represent the data. Let's pick a `Scatter` chart to start."
293 ]
294 },
295 {
296 "cell_type": "code",
297 "execution_count": null,
298 "metadata": {},
299 "outputs": [],
300 "source": [
301 "from bqplot import Scatter"
302 ]
303 },
304 {
305 "cell_type": "code",
306 "execution_count": null,
307 "metadata": {},
308 "outputs": [],
309 "source": [
310 "scatter_chart = Scatter(x=x_data, y=y_data, scales={'x': x_sc, 'y': y_sc})"
311 ]
312 },
313 {
314 "cell_type": "markdown",
315 "metadata": {},
316 "source": [
317 "Most of the time, the actual `Figure` coordinates don't really mean anything to us. So, what we need is the visual representation of our `Scale`, which is called an `Axis`."
318 ]
319 },
320 {
321 "cell_type": "code",
322 "execution_count": null,
323 "metadata": {},
324 "outputs": [],
325 "source": [
326 "from bqplot import Axis"
327 ]
328 },
329 {
330 "cell_type": "code",
331 "execution_count": null,
332 "metadata": {},
333 "outputs": [],
334 "source": [
335 "x_ax = Axis(label='X', scale=x_sc)\n",
336 "y_ax = Axis(label='Y', scale=y_sc, orientation='vertical')"
337 ]
338 },
339 {
340 "cell_type": "markdown",
341 "metadata": {},
342 "source": [
343 "And finally, we put it all together on a canvas, which is called a `Figure`."
344 ]
345 },
346 {
347 "cell_type": "code",
348 "execution_count": null,
349 "metadata": {},
350 "outputs": [],
351 "source": [
352 "from bqplot import Figure"
353 ]
354 },
355 {
356 "cell_type": "code",
357 "execution_count": null,
358 "metadata": {},
359 "outputs": [],
360 "source": [
361 "fig = Figure(marks=[scatter_chart], title='A Figure', axes=[x_ax, y_ax])\n",
362 "fig"
363 ]
364 },
365 {
366 "cell_type": "markdown",
367 "metadata": {},
368 "source": [
369 "The IPython display machinery displays the last returned value of a cell. If you wish to explicitly display a widget, you can call `IPython.display.display`."
370 ]
371 },
372 {
373 "cell_type": "code",
374 "execution_count": null,
375 "metadata": {},
376 "outputs": [],
377 "source": [
378 "from IPython.display import display"
379 ]
380 },
381 {
382 "cell_type": "code",
383 "execution_count": null,
384 "metadata": {},
385 "outputs": [],
386 "source": [
387 "display(fig)"
388 ]
389 },
390 {
391 "cell_type": "markdown",
392 "metadata": {},
393 "source": [
394 "Now, that the plot has been generated, we can control every single attribute of it. Let's say we wanted to color the chart based on some other data."
395 ]
396 },
397 {
398 "cell_type": "code",
399 "execution_count": null,
400 "metadata": {},
401 "outputs": [],
402 "source": [
403 "# First, we generate some random color data.\n",
404 "color_data = np.random.randint(0, 2, size=100)"
405 ]
406 },
407 {
408 "cell_type": "markdown",
409 "metadata": {},
410 "source": [
411 "Now, we define a ColorScale to map the color_data to actual colors"
412 ]
413 },
414 {
415 "cell_type": "code",
416 "execution_count": null,
417 "metadata": {},
418 "outputs": [],
419 "source": [
420 "from bqplot import ColorScale"
421 ]
422 },
423 {
424 "cell_type": "code",
425 "execution_count": null,
426 "metadata": {},
427 "outputs": [],
428 "source": [
429 "# The colors trait controls the actual colors we want to map to. It can also take a min, mid, max list of\n",
430 "# colors to be interpolated between for continuous data.\n",
431 "col_sc = ColorScale(colors=['MediumSeaGreen', 'Red'])"
432 ]
433 },
434 {
435 "cell_type": "code",
436 "execution_count": null,
437 "metadata": {},
438 "outputs": [],
439 "source": [
440 "scatter_chart.scales = {'x': x_sc, 'y': y_sc, 'color': col_sc}\n",
441 "# We pass the color data to the Scatter Chart through it's color attribute\n",
442 "scatter_chart.color = color_data"
443 ]
444 },
445 {
446 "cell_type": "markdown",
447 "metadata": {
448 "collapsed": true
449 },
450 "source": [
451 "The grammar of graphics framework allows us to overlay multiple visualizations on a single `Figure` by having the visualization share the `Scales`. So, for example, if we had a `Bar` chart that we would like to plot alongside the `Scatter` plot, we just pass it the same `Scales`."
452 ]
453 },
454 {
455 "cell_type": "code",
456 "execution_count": null,
457 "metadata": {},
458 "outputs": [],
459 "source": [
460 "from bqplot import Bars"
461 ]
462 },
463 {
464 "cell_type": "code",
465 "execution_count": null,
466 "metadata": {},
467 "outputs": [],
468 "source": [
469 "new_size = 50\n",
470 "scale = 100.\n",
471 "x_data_new = np.arange(new_size)\n",
472 "y_data_new = np.cumsum(np.random.randn(new_size) * scale)"
473 ]
474 },
475 {
476 "cell_type": "code",
477 "execution_count": null,
478 "metadata": {},
479 "outputs": [],
480 "source": [
481 "# All we need to do to add a bar chart to the Figure is pass the same scales to the Mark\n",
482 "bar_chart = Bars(x=x_data_new, y=y_data_new, scales={'x': x_sc, 'y': y_sc})"
483 ]
484 },
485 {
486 "cell_type": "markdown",
487 "metadata": {},
488 "source": [
489 "Finally, we add the new `Mark` to the `Figure` to update the plot!"
490 ]
491 },
492 {
493 "cell_type": "code",
494 "execution_count": null,
495 "metadata": {},
496 "outputs": [],
497 "source": [
498 "fig.marks = [scatter_chart, bar_chart]"
499 ]
500 }
501 ],
502 "metadata": {
503 "anaconda-cloud": {},
504 "kernelspec": {
505 "display_name": "Python 3",
506 "language": "python",
507 "name": "python3"
508 },
509 "language_info": {
510 "codemirror_mode": {
511 "name": "ipython",
512 "version": 3
513 },
514 "file_extension": ".py",
515 "mimetype": "text/x-python",
516 "name": "python",
517 "nbconvert_exporter": "python",
518 "pygments_lexer": "ipython3",
519 "version": "3.7.6"
520 }
521 },
522 "nbformat": 4,
523 "nbformat_minor": 1
524 }