{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "Examples taken from:\n", "https://github.com/bloomberg/bqplot" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "tags": [ "parameters" ] }, "outputs": [], "source": [ "flex_title = \"bqplot plots\"\n", "flex_orientation = \"rows\"\n", "flex_source_code = \"https://github.com/danielfrg/jupyter-flex/blob/master/examples/plots/bqplot.ipynb\"" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import numpy as np\n", "import pandas as pd\n", "from pandas import date_range\n", "from bqplot import *" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "size = 100\n", "np.random.seed(0)\n", "\n", "x_data = range(size)\n", "y_data = np.random.randn(size)\n", "y_data_2 = np.random.randn(size)\n", "y_data_3 = np.cumsum(np.random.randn(size) * 100.)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Bars" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Row 1" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Basic Bar Chart" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "tags": [ "chart" ] }, "outputs": [], "source": [ "x_ord = OrdinalScale()\n", "y_sc = LinearScale()\n", "\n", "bar = Bars(x=np.arange(10), y=np.random.rand(10), scales={'x': x_ord, 'y': y_sc})\n", "ax_x = Axis(scale=x_ord)\n", "ax_y = Axis(scale=y_sc, tick_format='0.2f', orientation='vertical')\n", "\n", "Figure(marks=[bar], axes=[ax_x, ax_y], padding_x=0.025, padding_y=0.025)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Stacked Bar Chart for 2-d data" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "tags": [ "chart" ] }, "outputs": [], "source": [ "x_ord = OrdinalScale()\n", "y_sc = LinearScale()\n", "\n", "bar = Bars(x=x_data, y=[y_data[:20], y_data_2[:20]], \n", " scales={'x': x_ord, 'y': y_sc}, padding=0.2,\n", " colors=CATEGORY10)\n", "ax_x = Axis(scale=x_ord)\n", "ax_y = Axis(scale=y_sc, orientation='vertical', tick_format='0.2f')\n", "\n", "Figure(marks=[bar], axes=[ax_x, ax_y])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Row 2" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Representing additional dimension using Color" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "tags": [ "chart" ] }, "outputs": [], "source": [ "# In this example, the color is just the magnitude of the y data\n", "x_ord = OrdinalScale()\n", "y_sc = LinearScale()\n", "col_sc = ColorScale(scheme='Reds')\n", "\n", "bar = Bars(x=x_data[:20], y=y_data[:20], color=np.abs(y_data[:20]),\n", " scales={'x': x_ord, 'y': y_sc, 'color': col_sc}, padding=0.2)\n", "ax_x = Axis(scale=x_ord)\n", "ax_y = Axis(scale=y_sc, orientation='vertical', tick_format='0.2f')\n", "ax_c = ColorAxis(scale=col_sc, tick_format='0.2f')\n", "\n", "margin = dict(top=50, bottom=80, left=50, right=50)\n", "\n", "Figure(marks=[bar], axes=[ax_x, ax_y, ax_c], fig_margin=margin)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Adding color for 2-d data" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "tags": [ "chart" ] }, "outputs": [], "source": [ "# By default color is applied along the axis=1\n", "x_ord = OrdinalScale()\n", "y_sc = LinearScale()\n", "col_sc = ColorScale(scheme='Reds')\n", "\n", "y_vals = [y_data[:20], y_data_2[:20], y_data_3[:20] / 100.0]\n", "color_data = np.mean(y_vals, axis=1)\n", "\n", "bar = Bars(x=x_data, y=y_vals, color=color_data, \n", " scales={'x': x_ord, 'y': y_sc, 'color': col_sc}, padding=0.2,\n", " labels=['Dim 1', 'Dim 2', 'Dim 3'], display_legend=True)\n", "ax_x = Axis(scale=x_ord)\n", "ax_y = Axis(scale=y_sc, orientation='vertical', tick_format='0.2f')\n", "ax_c = ColorAxis(scale=col_sc, tick_format='0.2f')\n", "\n", "margin = dict(top=50, bottom=80, left=50, right=50)\n", "Figure(marks=[bar], axes=[ax_x, ax_y, ax_c], fig_margin=margin)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Lines" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Row 1" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Basic Line Chart" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "security_1 = np.cumsum(np.random.randn(150)) + 100.\n", "security_2 = np.cumsum(np.random.randn(150)) + 100." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "tags": [ "chart" ] }, "outputs": [], "source": [ "sc_x = LinearScale()\n", "sc_y = LinearScale()\n", "\n", "line = Lines(x=np.arange(len(security_1)), y=security_1,\n", " scales={'x': sc_x, 'y': sc_y})\n", "ax_x = Axis(scale=sc_x, label='Index')\n", "ax_y = Axis(scale=sc_y, orientation='vertical', label='y-values of Security 1')\n", "\n", "Figure(marks=[line], axes=[ax_x, ax_y], title='Security 1')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Time Series" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Here we define the dates we would like to use\n", "dates = date_range(start='01-01-2007', periods=150)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "tags": [ "chart" ] }, "outputs": [], "source": [ "dt_x = DateScale()\n", "sc_y = LinearScale()\n", "\n", "time_series = Lines(x=dates, y=security_1, scales={'x': dt_x, 'y': sc_y})\n", "ax_x = Axis(scale=dt_x, label='Date')\n", "ax_y = Axis(scale=sc_y, orientation='vertical', label='Security 1')\n", "\n", "Figure(marks=[time_series], axes=[ax_x, ax_y], title='A Time Series Plot')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Row 2" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Coloring Lines according to data" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "x_dt = DateScale()\n", "y_sc = LinearScale()\n", "col_sc = ColorScale(colors=['Red', 'Green'])" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "dates_color = date_range(start='06-01-2007', periods=150)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "securities = 100. + np.cumsum(np.random.randn(150, 10), axis=0)\n", "positions = np.random.randint(0, 2, size=10)\n", "# Here we generate 10 random price series and 10 random positions" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# We pass the color scale and the color data to the lines\n", "line = Lines(x=dates_color, y=securities.T, \n", " scales={'x': x_dt, 'y': y_sc, 'color': col_sc}, color=positions,\n", " labels=['Security 1', 'Security 2'])" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "tags": [ "chart" ] }, "outputs": [], "source": [ "ax_x = Axis(scale=x_dt, label='Date')\n", "ax_y = Axis(scale=y_sc, orientation='vertical', label='Security 1')\n", "\n", "Figure(marks=[line], axes=[ax_x, ax_y], legend_location='top-left')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "line.color = None" ] }, { "cell_type": "markdown", "metadata": { "tags": [ "orientation=columns" ] }, "source": [ "# Scatter" ] }, { "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": {}, "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": { "tags": [ "chart" ] }, "outputs": [], "source": [ "sc_x = DateScale()\n", "sc_y = LinearScale()\n", "\n", "scatt = Scatter(x=dates_all, y=sec2_levels, scales={'x': sc_x, 'y': sc_y})\n", "ax_x = Axis(scale=sc_x, label='Date')\n", "ax_y = Axis(scale=sc_y, orientation='vertical', tick_format='0.0f', label='Security 2')\n", "\n", "Figure(marks=[scatt], axes=[ax_x, ax_y])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Linear Scale for Color Data" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "tags": [ "chart" ] }, "outputs": [], "source": [ "sc_x = DateScale()\n", "sc_y = LinearScale()\n", "\n", "sc_c1 = ColorScale()\n", "scatter = Scatter(x=dates_all, y=sec2_levels, color=sec1_returns,\n", " scales={'x': sc_x, 'y': sc_y, 'color': sc_c1}, \n", " stroke='black')\n", "\n", "ax_y = Axis(label='Security 2', scale=sc_y, \n", " orientation='vertical', side='left')\n", "\n", "ax_x = Axis(label='Date', scale=sc_x, num_ticks=10, label_location='end')\n", "ax_c = ColorAxis(scale=sc_c1, tick_format='0.2%', label='Returns', orientation='vertical', side='right')\n", "\n", "m_chart = dict(top=50, bottom=70, left=50, right=100)\n", "\n", "Figure(axes=[ax_x, ax_c, ax_y], marks=[scatter], fig_margin=m_chart,\n", " title='Scatter of Security 2 vs Dates')" ] }, { "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", "ax_c.tick_format = '0.0f'\n", "ax_c.label = 'Security 2'" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "## Changing the range of the color scale\n", "sc_c1.colors = ['blue', 'green', 'orange']" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Col 2" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Moving points in Scatter" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from ipywidgets import Label" ] }, { "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", "sc_x = LinearScale()\n", "sc_y = LinearScale()\n", "\n", "scat = Scatter(x=x_data[:10], y=y_data[:10], scales={'x': sc_x, 'y': sc_y}, colors=['orange'],\n", " enable_move=True)\n", "lin = Lines(x=[], y=[], scales={'x': sc_x, 'y': sc_y}, 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", "# 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", "ax_x = Axis(scale=sc_x)\n", "ax_y = Axis(scale=sc_y, tick_format='0.2f', orientation='vertical')\n", "\n", "fig = Figure(marks=[scat, lin], axes=[ax_x, ax_y])" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "## In this case on drag, the line updates as you move the points.\n", "scat.update_on_move = True" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "latex_widget = Label(color='Green', font_size='16px')\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)\n", "scat.on_drag(callback_help)\n", "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": "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": "code", "execution_count": null, "metadata": { "tags": [ "chart" ] }, "outputs": [], "source": [ "from ipywidgets import ToggleButtons, VBox\n", "\n", "interact_control = ToggleButtons(options=['Add', 'Delete', 'Drag XY', 'Drag X', 'Drag Y'],\n", " style={'button_width': '120px'})\n", "\n", "def change_interact(change):\n", " interact_parameters = {\n", " 'Add': {'interactions': {'click': 'add'},\n", " 'enable_move': False},\n", " 'Delete': {'interactions': {'click': 'delete'},\n", " 'enable_move': False},\n", " 'Drag XY': {'interactions': {'click': None},\n", " 'enable_move': True,\n", " 'restrict_x': False,\n", " 'restrict_y': False},\n", " 'Drag X': {'interactions': {'click': None},\n", " 'enable_move': True,\n", " 'restrict_x': True,\n", " 'restrict_y': False},\n", " 'Drag Y': {'interactions': {'click': None},\n", " 'enable_move': True,\n", " 'restrict_x': False,\n", " 'restrict_y': True}\n", " }\n", " for param, value in interact_parameters[interact_control.value].items():\n", " setattr(scat, param, value)\n", " \n", "interact_control.observe(change_interact, names='value')\n", "\n", "fig.title = 'Adding/Deleting/Moving points'\n", "VBox([fig, interact_control])" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "celltoolbar": "Tags", "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.7.6" } }, "nbformat": 4, "nbformat_minor": 4 }