Debian Codegraph @

bqplot/examples/Marks/Pyplot/Scatter.ipynb

raw
1 {
2 "cells": [
3 {
4 "cell_type": "code",
5 "execution_count": null,
6 "metadata": {
7 "input_collapsed": false
8 },
9 "outputs": [],
10 "source": [
11 "from __future__ import print_function\n",
12 "import numpy as np\n",
13 "import pandas as pd\n",
14 "\n",
15 "import ipywidgets\n",
16 "\n",
17 "from bqplot import (ColorScale, DateColorScale, OrdinalColorScale, \n",
18 " LinearScale, Tooltip)\n",
19 "import bqplot.pyplot as plt"
20 ]
21 },
22 {
23 "cell_type": "markdown",
24 "metadata": {},
25 "source": [
26 "## Get Data"
27 ]
28 },
29 {
30 "cell_type": "code",
31 "execution_count": null,
32 "metadata": {},
33 "outputs": [],
34 "source": [
35 "price_data = pd.DataFrame(np.cumsum(np.random.randn(150, 2).dot([[1.0, -0.8], [-0.8, 1.0]]), axis=0) + 100,\n",
36 " columns=['Security 1', 'Security 2'], index=pd.date_range(start='01-01-2007', periods=150))\n",
37 "size = 100\n",
38 "np.random.seed(0)\n",
39 "x_data = range(size)\n",
40 "y_data = np.cumsum(np.random.randn(size) * 100.0)\n",
41 "ord_keys = np.array(['A', 'B', 'C', 'D', 'E', 'F'])\n",
42 "ordinal_data = np.random.randint(5, size=size)"
43 ]
44 },
45 {
46 "cell_type": "code",
47 "execution_count": null,
48 "metadata": {
49 "input_collapsed": false
50 },
51 "outputs": [],
52 "source": [
53 "symbols = ['Security 1', 'Security 2']\n",
54 "\n",
55 "dates_all = price_data.index.values\n",
56 "dates_all_t = dates_all[1:]\n",
57 "sec1_levels = np.array(price_data[symbols[0]].values.flatten())\n",
58 "log_sec1 = np.log(sec1_levels)\n",
59 "sec1_returns = log_sec1[1:] - log_sec1[:-1]\n",
60 "\n",
61 "sec2_levels = np.array(price_data[symbols[1]].values.flatten())"
62 ]
63 },
64 {
65 "cell_type": "markdown",
66 "metadata": {},
67 "source": [
68 "# Basic Scatter"
69 ]
70 },
71 {
72 "cell_type": "code",
73 "execution_count": null,
74 "metadata": {},
75 "outputs": [],
76 "source": [
77 "fig = plt.figure()\n",
78 "axes_options = {'x': {'label': 'Date'}, 'y': {'label': 'Security 2'}}\n",
79 "scatt = plt.scatter(dates_all, sec2_levels, axes_options=axes_options, stroke='black')\n",
80 "fig"
81 ]
82 },
83 {
84 "cell_type": "markdown",
85 "metadata": {},
86 "source": [
87 "## Changing the marker and adding text to each point of the scatter"
88 ]
89 },
90 {
91 "cell_type": "code",
92 "execution_count": null,
93 "metadata": {},
94 "outputs": [],
95 "source": [
96 "fig = plt.figure(padding_x=0.025)\n",
97 "scatt = plt.scatter(x_data[:10], y_data[:10], names=np.arange(10),\n",
98 " colors=['red'], marker='cross')\n",
99 "fig"
100 ]
101 },
102 {
103 "cell_type": "markdown",
104 "metadata": {},
105 "source": [
106 "## Changing the opacity of each marker"
107 ]
108 },
109 {
110 "cell_type": "code",
111 "execution_count": null,
112 "metadata": {},
113 "outputs": [],
114 "source": [
115 "scatt.opacities = [0.3, 0.5, 1.]"
116 ]
117 },
118 {
119 "cell_type": "markdown",
120 "metadata": {},
121 "source": [
122 "# Representing additional dimensions of data"
123 ]
124 },
125 {
126 "cell_type": "markdown",
127 "metadata": {
128 "input_collapsed": false
129 },
130 "source": [
131 "## Linear Scale for Color Data"
132 ]
133 },
134 {
135 "cell_type": "code",
136 "execution_count": null,
137 "metadata": {
138 "input_collapsed": false
139 },
140 "outputs": [],
141 "source": [
142 "# give extra margin on the right to accommodate the color axis\n",
143 "fig_margin = dict(top=50, bottom=70, left=50, right=100)\n",
144 "fig = plt.figure(title='Scatter', fig_margin=fig_margin)\n",
145 "plt.scales(scales={'color': ColorScale()})\n",
146 "\n",
147 "axes_options = {'x': dict(label='Date', num_ticks=10, label_location='end'), \n",
148 " 'y': dict(label='Security 2', sid='left'),\n",
149 " 'color': dict(tick_format='0.2%', \n",
150 " label='Returns', \n",
151 " orientation='vertical', \n",
152 " side='right')}\n",
153 "scatter = plt.scatter(dates_all, sec2_levels, color=sec1_returns, \n",
154 " stroke='black', axes_options=axes_options)\n",
155 "fig"
156 ]
157 },
158 {
159 "cell_type": "code",
160 "execution_count": null,
161 "metadata": {},
162 "outputs": [],
163 "source": [
164 "## Changing the default color. \n",
165 "scatter.colors = ['blue'] # In this case, the dot with the highest X changes to blue."
166 ]
167 },
168 {
169 "cell_type": "code",
170 "execution_count": null,
171 "metadata": {},
172 "outputs": [],
173 "source": [
174 "## setting the fill to be empty\n",
175 "scatter.stroke = None\n",
176 "scatter.fill = False"
177 ]
178 },
179 {
180 "cell_type": "code",
181 "execution_count": null,
182 "metadata": {},
183 "outputs": [],
184 "source": [
185 "## Setting the fill back\n",
186 "scatter.stroke = 'black'\n",
187 "scatter.fill = True"
188 ]
189 },
190 {
191 "cell_type": "code",
192 "execution_count": null,
193 "metadata": {},
194 "outputs": [],
195 "source": [
196 "## Changing the color to a different variable\n",
197 "scatter.color = sec2_levels\n",
198 "color_axis = [a for a in fig.axes if type(a.scale) == ColorScale][0]\n",
199 "color_axis.tick_format = '0.0f'\n",
200 "color_axis.label = 'Security 2'"
201 ]
202 },
203 {
204 "cell_type": "code",
205 "execution_count": null,
206 "metadata": {},
207 "outputs": [],
208 "source": [
209 "## Changing the range of the color scale\n",
210 "color_axis.scale.colors = ['blue', 'green', 'orange']"
211 ]
212 },
213 {
214 "cell_type": "markdown",
215 "metadata": {},
216 "source": [
217 "## Date Scale for Color Data"
218 ]
219 },
220 {
221 "cell_type": "code",
222 "execution_count": null,
223 "metadata": {},
224 "outputs": [],
225 "source": [
226 "fig = plt.figure(fig_margin=dict(top=50, bottom=80, left=50, right=50))\n",
227 "plt.scales(scales={'color': DateColorScale(scheme='Reds')})\n",
228 "\n",
229 "axes_options = {'x': dict(label='Security 2'),\n",
230 " 'y': dict(label='Security 1'),\n",
231 " 'color': dict(tick_format='0.2%', label='Date', num_ticks=5)\n",
232 " }\n",
233 "scatter = plt.scatter(sec2_levels, sec1_levels, color=dates_all, \n",
234 " default_size=128, stroke='black',\n",
235 " axes_options=axes_options)\n",
236 "fig"
237 ]
238 },
239 {
240 "cell_type": "markdown",
241 "metadata": {
242 "input_collapsed": false
243 },
244 "source": [
245 "## Ordinal Scale for Color"
246 ]
247 },
248 {
249 "cell_type": "code",
250 "execution_count": null,
251 "metadata": {
252 "input_collapsed": false
253 },
254 "outputs": [],
255 "source": [
256 "factor = int(np.ceil(len(sec2_levels) * 1.0 / len(ordinal_data)))\n",
257 "ordinal_data = np.tile(ordinal_data, factor)\n",
258 "\n",
259 "fig = plt.figure(fig_margin=dict(top=50, bottom=70, left=100, right=100))\n",
260 "plt.scales(scales={'color': OrdinalColorScale(colors=['DodgerBlue', 'SeaGreen', 'Yellow', 'HotPink', 'OrangeRed'])})\n",
261 "\n",
262 "axes_options = {'x': dict(label='Security 2', label_location='end'),\n",
263 " 'y': dict(label='Security 1 Returns', tick_format='.0%'),\n",
264 " 'color': dict(label='Class', side='right')\n",
265 " }\n",
266 "scatter2 = plt.scatter(sec2_levels[1:],\n",
267 " sec1_returns,\n",
268 " color=ordinal_data,\n",
269 " stroke='black',\n",
270 " axes_options=axes_options)\n",
271 "fig"
272 ]
273 },
274 {
275 "cell_type": "code",
276 "execution_count": null,
277 "metadata": {},
278 "outputs": [],
279 "source": [
280 "color_axis = [a for a in fig.axes if isinstance(a.scale, ColorScale)][0]\n",
281 "color_axis.tick_format = '0.2f'\n",
282 "color_axis.scale.colors = ['blue', 'red', 'green', 'yellow', 'orange']"
283 ]
284 },
285 {
286 "cell_type": "markdown",
287 "metadata": {},
288 "source": [
289 "## Setting size and opacity based on data"
290 ]
291 },
292 {
293 "cell_type": "code",
294 "execution_count": null,
295 "metadata": {
296 "input_collapsed": false
297 },
298 "outputs": [],
299 "source": [
300 "fig = plt.figure()\n",
301 "plt.scales(scales={'opacity': LinearScale(), 'size': LinearScale()})\n",
302 "axes_options = {'x': {'label': 'Security 2'}, 'y': {'label': 'Security 1'}}\n",
303 "\n",
304 "scatter2 = plt.scatter(sec2_levels[1:], sec1_levels, opacity=[], \n",
305 " size=sec1_returns,\n",
306 " default_size=128, colors=['orangered'], \n",
307 " stroke='black', axes_options=axes_options)\n",
308 "fig"
309 ]
310 },
311 {
312 "cell_type": "code",
313 "execution_count": null,
314 "metadata": {},
315 "outputs": [],
316 "source": [
317 "## Changing the opacity of the scatter\n",
318 "scatter2.opacities = [0.5, 0.3, 0.1]"
319 ]
320 },
321 {
322 "cell_type": "code",
323 "execution_count": null,
324 "metadata": {},
325 "outputs": [],
326 "source": [
327 "## Resetting the size for the scatter\n",
328 "scatter2.size=None"
329 ]
330 },
331 {
332 "cell_type": "code",
333 "execution_count": null,
334 "metadata": {},
335 "outputs": [],
336 "source": [
337 "## Resetting the opacity and setting the opacity according to the date\n",
338 "scatter2.opacities = [1.0]"
339 ]
340 },
341 {
342 "cell_type": "code",
343 "execution_count": null,
344 "metadata": {},
345 "outputs": [],
346 "source": [
347 "scatter2.opacity = dates_all"
348 ]
349 },
350 {
351 "cell_type": "markdown",
352 "metadata": {},
353 "source": [
354 "## Changing the skew of the marker"
355 ]
356 },
357 {
358 "cell_type": "code",
359 "execution_count": null,
360 "metadata": {},
361 "outputs": [],
362 "source": [
363 "fig = plt.figure(animation_duration=1000)\n",
364 "plt.scales(scales={'skew': LinearScale()})\n",
365 "axes_options = {'x': {'label': 'Security 2'}, 'y': {'label': 'Security 1'}}\n",
366 "scatter = plt.scatter(sec2_levels[1:], sec1_levels,\n",
367 " skew=sec1_returns, stroke=\"black\",\n",
368 " colors=['gold'], default_size=200, \n",
369 " marker='rectangle', default_skew=0,\n",
370 " axes_options=axes_options)\n",
371 "fig"
372 ]
373 },
374 {
375 "cell_type": "code",
376 "execution_count": null,
377 "metadata": {},
378 "outputs": [],
379 "source": [
380 "scatter.skew = None"
381 ]
382 },
383 {
384 "cell_type": "code",
385 "execution_count": null,
386 "metadata": {},
387 "outputs": [],
388 "source": [
389 "scatter.skew = sec1_returns"
390 ]
391 },
392 {
393 "cell_type": "markdown",
394 "metadata": {},
395 "source": [
396 "## Rotation scale"
397 ]
398 },
399 {
400 "cell_type": "code",
401 "execution_count": null,
402 "metadata": {},
403 "outputs": [],
404 "source": [
405 "x1 = np.linspace(-1, 1, 30)\n",
406 "y1 = np.linspace(-1, 1, 30)\n",
407 "x, y = np.meshgrid(x1,y1)\n",
408 "x, y = x.flatten(), y.flatten()\n",
409 "rot = x**2 + y**2\n",
410 "color = x - y\n",
411 "\n",
412 "fig = plt.figure(animation_duration=1000)\n",
413 "plt.scales(scales={'color': ColorScale(scheme='Reds'), 'rotation': LinearScale()})\n",
414 "scatter = plt.scatter(x, y, rotation=rot, color=color,\n",
415 " stroke=\"black\", default_size=200, \n",
416 " marker='arrow', default_skew=0.5,)\n",
417 "fig"
418 ]
419 },
420 {
421 "cell_type": "code",
422 "execution_count": null,
423 "metadata": {},
424 "outputs": [],
425 "source": [
426 "scatter.rotation = 1.0 / (x ** 2 + y ** 2 + 1)"
427 ]
428 },
429 {
430 "cell_type": "markdown",
431 "metadata": {},
432 "source": [
433 "# Scatter Chart Interactions"
434 ]
435 },
436 {
437 "cell_type": "markdown",
438 "metadata": {},
439 "source": [
440 "## Moving points in Scatter"
441 ]
442 },
443 {
444 "cell_type": "code",
445 "execution_count": null,
446 "metadata": {},
447 "outputs": [],
448 "source": [
449 "## Enabling moving of points in scatter. Try to click and drag any of the points in the scatter and \n",
450 "## notice the line representing the mean of the data update\n",
451 "fig = plt.figure()\n",
452 "scat = plt.scatter(x_data[:10], y_data[:10], colors=['orange'], enable_move=True)\n",
453 "lin = plt.plot([], [], line_style='dotted', colors=['orange'])\n",
454 "\n",
455 "def update_line(change=None):\n",
456 " with lin.hold_sync():\n",
457 " lin.x = [np.min(scat.x), np.max(scat.x)]\n",
458 " lin.y = [np.mean(scat.y), np.mean(scat.y)]\n",
459 "\n",
460 "update_line()\n",
461 "\n",
462 "# update line on change of x or y of scatter\n",
463 "scat.observe(update_line, names=['x'])\n",
464 "scat.observe(update_line, names=['y'])\n",
465 "\n",
466 "fig"
467 ]
468 },
469 {
470 "cell_type": "code",
471 "execution_count": null,
472 "metadata": {},
473 "outputs": [],
474 "source": [
475 "latex_widget = ipywidgets.Label()\n",
476 "\n",
477 "def callback_help(name, value):\n",
478 " latex_widget.value = str(value)\n",
479 " \n",
480 "latex_widget"
481 ]
482 },
483 {
484 "cell_type": "code",
485 "execution_count": null,
486 "metadata": {},
487 "outputs": [],
488 "source": [
489 "scat.on_drag_start(callback_help)"
490 ]
491 },
492 {
493 "cell_type": "code",
494 "execution_count": null,
495 "metadata": {},
496 "outputs": [],
497 "source": [
498 "scat.on_drag(callback_help)"
499 ]
500 },
501 {
502 "cell_type": "code",
503 "execution_count": null,
504 "metadata": {},
505 "outputs": [],
506 "source": [
507 "scat.on_drag_end(callback_help)"
508 ]
509 },
510 {
511 "cell_type": "code",
512 "execution_count": null,
513 "metadata": {},
514 "outputs": [],
515 "source": [
516 "## Restricting movement to only along the Y-axis\n",
517 "scat.restrict_y = True"
518 ]
519 },
520 {
521 "cell_type": "markdown",
522 "metadata": {},
523 "source": [
524 "## Adding points to Scatter"
525 ]
526 },
527 {
528 "cell_type": "code",
529 "execution_count": null,
530 "metadata": {},
531 "outputs": [],
532 "source": [
533 "## Enabling adding the points to Scatter. Try clicking anywhere on the scatter to add points\n",
534 "with scat.hold_sync():\n",
535 " scat.enable_move = False\n",
536 " scat.interactions = {'click': 'add'}"
537 ]
538 },
539 {
540 "cell_type": "markdown",
541 "metadata": {},
542 "source": [
543 "## Updating X and Y while moving the point"
544 ]
545 },
546 {
547 "cell_type": "code",
548 "execution_count": null,
549 "metadata": {},
550 "outputs": [],
551 "source": [
552 "## In this case on drag, the line updates as you move the points.\n",
553 "with scat.hold_sync():\n",
554 " scat.enable_move = True\n",
555 " scat.update_on_move = True\n",
556 " scat.interactions = {'click': None}"
557 ]
558 },
559 {
560 "cell_type": "markdown",
561 "metadata": {},
562 "source": [
563 "## Custom event on end of drag"
564 ]
565 },
566 {
567 "cell_type": "code",
568 "execution_count": null,
569 "metadata": {},
570 "outputs": [],
571 "source": [
572 "## Whenever drag is ended, there is a custom event dispatched which can be listened to.\n",
573 "## try dragging a point and see the data associated with the event being printed\n",
574 "def test_func(self, content):\n",
575 " print(\"received drag end\", content)\n",
576 "\n",
577 "scat.on_drag_end(test_func)"
578 ]
579 },
580 {
581 "cell_type": "markdown",
582 "metadata": {
583 "collapsed": true
584 },
585 "source": [
586 "## Adding tooltip and custom hover style"
587 ]
588 },
589 {
590 "cell_type": "code",
591 "execution_count": null,
592 "metadata": {},
593 "outputs": [],
594 "source": [
595 "x_data = x_data[:50]\n",
596 "y_data = y_data[:50]\n",
597 "\n",
598 "fig = plt.figure()\n",
599 "def_tt = Tooltip(fields=['x', 'y'], formats=['', '.2f'])\n",
600 "scatter_chart = plt.scatter(x_data, y_data, colors=['dodgerblue'],\n",
601 " tooltip=def_tt, stroke='black',\n",
602 " unhovered_style={'opacity': 0.5})\n",
603 "fig"
604 ]
605 },
606 {
607 "cell_type": "code",
608 "execution_count": null,
609 "metadata": {},
610 "outputs": [],
611 "source": [
612 "## removing field names from the tooltip\n",
613 "def_tt.show_labels = False"
614 ]
615 },
616 {
617 "cell_type": "code",
618 "execution_count": null,
619 "metadata": {},
620 "outputs": [],
621 "source": [
622 "## changing the fields displayed in the tooltip\n",
623 "def_tt.fields = ['y']"
624 ]
625 }
626 ],
627 "metadata": {
628 "anaconda-cloud": {},
629 "kernelspec": {
630 "display_name": "Python 3",
631 "language": "python",
632 "name": "python3"
633 },
634 "language_info": {
635 "codemirror_mode": {
636 "name": "ipython",
637 "version": 3
638 },
639 "file_extension": ".py",
640 "mimetype": "text/x-python",
641 "name": "python",
642 "nbconvert_exporter": "python",
643 "pygments_lexer": "ipython3",
644 "version": "3.8.2"
645 }
646 },
647 "nbformat": 4,
648 "nbformat_minor": 1
649 }