Debian Codegraph @

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