{ "cells": [ { "cell_type": "code", "execution_count": null, "metadata": { "input_collapsed": false }, "outputs": [], "source": [ "from __future__ import print_function\n", "import numpy as np\n", "import pandas as pd\n", "\n", "import ipywidgets\n", "\n", "from bqplot import (ColorScale, DateColorScale, OrdinalColorScale, \n", " LinearScale, Tooltip)\n", "import bqplot.pyplot as plt" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Get Data" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "price_data = pd.DataFrame(np.cumsum(np.random.randn(150, 2).dot([[1.0, -0.8], [-0.8, 1.0]]), axis=0) + 100,\n", " columns=['Security 1', 'Security 2'], index=pd.date_range(start='01-01-2007', periods=150))\n", "size = 100\n", "np.random.seed(0)\n", "x_data = range(size)\n", "y_data = np.cumsum(np.random.randn(size) * 100.0)\n", "ord_keys = np.array(['A', 'B', 'C', 'D', 'E', 'F'])\n", "ordinal_data = np.random.randint(5, size=size)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "input_collapsed": false }, "outputs": [], "source": [ "symbols = ['Security 1', 'Security 2']\n", "\n", "dates_all = price_data.index.values\n", "dates_all_t = dates_all[1:]\n", "sec1_levels = np.array(price_data[symbols[0]].values.flatten())\n", "log_sec1 = np.log(sec1_levels)\n", "sec1_returns = log_sec1[1:] - log_sec1[:-1]\n", "\n", "sec2_levels = np.array(price_data[symbols[1]].values.flatten())" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Basic Scatter" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "fig = plt.figure()\n", "axes_options = {'x': {'label': 'Date'}, 'y': {'label': 'Security 2'}}\n", "scatt = plt.scatter(dates_all, sec2_levels, axes_options=axes_options, stroke='black')\n", "fig" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Changing the marker and adding text to each point of the scatter" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "fig = plt.figure(padding_x=0.025)\n", "scatt = plt.scatter(x_data[:10], y_data[:10], names=np.arange(10),\n", " colors=['red'], marker='cross')\n", "fig" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Changing the opacity of each marker" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "scatt.opacities = [0.3, 0.5, 1.]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Representing additional dimensions of data" ] }, { "cell_type": "markdown", "metadata": { "input_collapsed": false }, "source": [ "## Linear Scale for Color Data" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "input_collapsed": false }, "outputs": [], "source": [ "# give extra margin on the right to accommodate the color axis\n", "fig_margin = dict(top=50, bottom=70, left=50, right=100)\n", "fig = plt.figure(title='Scatter', fig_margin=fig_margin)\n", "plt.scales(scales={'color': ColorScale()})\n", "\n", "axes_options = {'x': dict(label='Date', num_ticks=10, label_location='end'), \n", " 'y': dict(label='Security 2', sid='left'),\n", " 'color': dict(tick_format='0.2%', \n", " label='Returns', \n", " orientation='vertical', \n", " side='right')}\n", "scatter = plt.scatter(dates_all, sec2_levels, color=sec1_returns, \n", " stroke='black', axes_options=axes_options)\n", "fig" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "## Changing the default color. \n", "scatter.colors = ['blue'] # In this case, the dot with the highest X changes to blue." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "## setting the fill to be empty\n", "scatter.stroke = None\n", "scatter.fill = False" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "## Setting the fill back\n", "scatter.stroke = 'black'\n", "scatter.fill = True" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "## Changing the color to a different variable\n", "scatter.color = sec2_levels\n", "color_axis = [a for a in fig.axes if type(a.scale) == ColorScale][0]\n", "color_axis.tick_format = '0.0f'\n", "color_axis.label = 'Security 2'" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "## Changing the range of the color scale\n", "color_axis.scale.colors = ['blue', 'green', 'orange']" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Date Scale for Color Data" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "fig = plt.figure(fig_margin=dict(top=50, bottom=80, left=50, right=50))\n", "plt.scales(scales={'color': DateColorScale(scheme='Reds')})\n", "\n", "axes_options = {'x': dict(label='Security 2'),\n", " 'y': dict(label='Security 1'),\n", " 'color': dict(tick_format='0.2%', label='Date', num_ticks=5)\n", " }\n", "scatter = plt.scatter(sec2_levels, sec1_levels, color=dates_all, \n", " default_size=128, stroke='black',\n", " axes_options=axes_options)\n", "fig" ] }, { "cell_type": "markdown", "metadata": { "input_collapsed": false }, "source": [ "## Ordinal Scale for Color" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "input_collapsed": false }, "outputs": [], "source": [ "factor = int(np.ceil(len(sec2_levels) * 1.0 / len(ordinal_data)))\n", "ordinal_data = np.tile(ordinal_data, factor)\n", "\n", "fig = plt.figure(fig_margin=dict(top=50, bottom=70, left=100, right=100))\n", "plt.scales(scales={'color': OrdinalColorScale(colors=['DodgerBlue', 'SeaGreen', 'Yellow', 'HotPink', 'OrangeRed'])})\n", "\n", "axes_options = {'x': dict(label='Security 2', label_location='end'),\n", " 'y': dict(label='Security 1 Returns', tick_format='.0%'),\n", " 'color': dict(label='Class', side='right')\n", " }\n", "scatter2 = plt.scatter(sec2_levels[1:],\n", " sec1_returns,\n", " color=ordinal_data,\n", " stroke='black',\n", " axes_options=axes_options)\n", "fig" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "color_axis = [a for a in fig.axes if isinstance(a.scale, ColorScale)][0]\n", "color_axis.tick_format = '0.2f'\n", "color_axis.scale.colors = ['blue', 'red', 'green', 'yellow', 'orange']" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Setting size and opacity based on data" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "input_collapsed": false }, "outputs": [], "source": [ "fig = plt.figure()\n", "plt.scales(scales={'opacity': LinearScale(), 'size': LinearScale()})\n", "axes_options = {'x': {'label': 'Security 2'}, 'y': {'label': 'Security 1'}}\n", "\n", "scatter2 = plt.scatter(sec2_levels[1:], sec1_levels, opacity=[], \n", " size=sec1_returns,\n", " default_size=128, colors=['orangered'], \n", " stroke='black', axes_options=axes_options)\n", "fig" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "## Changing the opacity of the scatter\n", "scatter2.opacities = [0.5, 0.3, 0.1]" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "## Resetting the size for the scatter\n", "scatter2.size=None" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "## Resetting the opacity and setting the opacity according to the date\n", "scatter2.opacities = [1.0]" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "scatter2.opacity = dates_all" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Changing the skew of the marker" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "fig = plt.figure(animation_duration=1000)\n", "plt.scales(scales={'skew': LinearScale()})\n", "axes_options = {'x': {'label': 'Security 2'}, 'y': {'label': 'Security 1'}}\n", "scatter = plt.scatter(sec2_levels[1:], sec1_levels,\n", " skew=sec1_returns, stroke=\"black\",\n", " colors=['gold'], default_size=200, \n", " marker='rectangle', default_skew=0,\n", " axes_options=axes_options)\n", "fig" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "scatter.skew = None" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "scatter.skew = sec1_returns" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Rotation scale" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "x1 = np.linspace(-1, 1, 30)\n", "y1 = np.linspace(-1, 1, 30)\n", "x, y = np.meshgrid(x1,y1)\n", "x, y = x.flatten(), y.flatten()\n", "rot = x**2 + y**2\n", "color = x - y\n", "\n", "fig = plt.figure(animation_duration=1000)\n", "plt.scales(scales={'color': ColorScale(scheme='Reds'), 'rotation': LinearScale()})\n", "scatter = plt.scatter(x, y, rotation=rot, color=color,\n", " stroke=\"black\", default_size=200, \n", " marker='arrow', default_skew=0.5,)\n", "fig" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "scatter.rotation = 1.0 / (x ** 2 + y ** 2 + 1)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Scatter Chart Interactions" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Moving points in Scatter" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "## Enabling moving of points in scatter. Try to click and drag any of the points in the scatter and \n", "## notice the line representing the mean of the data update\n", "fig = plt.figure()\n", "scat = plt.scatter(x_data[:10], y_data[:10], colors=['orange'], enable_move=True)\n", "lin = plt.plot([], [], line_style='dotted', colors=['orange'])\n", "\n", "def update_line(change=None):\n", " with lin.hold_sync():\n", " lin.x = [np.min(scat.x), np.max(scat.x)]\n", " lin.y = [np.mean(scat.y), np.mean(scat.y)]\n", "\n", "update_line()\n", "\n", "# update line on change of x or y of scatter\n", "scat.observe(update_line, names=['x'])\n", "scat.observe(update_line, names=['y'])\n", "\n", "fig" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "latex_widget = ipywidgets.Label()\n", "\n", "def callback_help(name, value):\n", " latex_widget.value = str(value)\n", " \n", "latex_widget" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "scat.on_drag_start(callback_help)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "scat.on_drag(callback_help)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "scat.on_drag_end(callback_help)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "## Restricting movement to only along the Y-axis\n", "scat.restrict_y = True" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Adding points to Scatter" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "## Enabling adding the points to Scatter. Try clicking anywhere on the scatter to add points\n", "with scat.hold_sync():\n", " scat.enable_move = False\n", " scat.interactions = {'click': 'add'}" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Updating X and Y while moving the point" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "## In this case on drag, the line updates as you move the points.\n", "with scat.hold_sync():\n", " scat.enable_move = True\n", " scat.update_on_move = True\n", " scat.interactions = {'click': None}" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Custom event on end of drag" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "## Whenever drag is ended, there is a custom event dispatched which can be listened to.\n", "## try dragging a point and see the data associated with the event being printed\n", "def test_func(self, content):\n", " print(\"received drag end\", content)\n", "\n", "scat.on_drag_end(test_func)" ] }, { "cell_type": "markdown", "metadata": { "collapsed": true }, "source": [ "## Adding tooltip and custom hover style" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "x_data = x_data[:50]\n", "y_data = y_data[:50]\n", "\n", "fig = plt.figure()\n", "def_tt = Tooltip(fields=['x', 'y'], formats=['', '.2f'])\n", "scatter_chart = plt.scatter(x_data, y_data, colors=['dodgerblue'],\n", " tooltip=def_tt, stroke='black',\n", " unhovered_style={'opacity': 0.5})\n", "fig" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "## removing field names from the tooltip\n", "def_tt.show_labels = False" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "## changing the fields displayed in the tooltip\n", "def_tt.fields = ['y']" ] } ], "metadata": { "anaconda-cloud": {}, "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.8.2" } }, "nbformat": 4, "nbformat_minor": 1 }