{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Plotting with Bokeh" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import numpy as np\n", "import pandas as pd\n", "import holoviews as hv\n", "from holoviews import dim, opts\n", "\n", "hv.extension('bokeh')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "One of the major design principles of HoloViews is that the declaration of data is completely independent from the plotting implementation. Bokeh provides a powerful platform to generate interactive plots using HTML5 canvas and WebGL, and is ideally suited towards interactive exploration of data. By combining the ease of generating interactive, high-dimensional visualizations with the interactive widgets and fast rendering provided by Bokeh, HoloViews becomes even more powerful.\n", "\n", "This user guide will cover various interactive features that bokeh provides which is not covered by the more general user guides, including interactive tools, linked axes and brushing and more. The general principles behind customizing plots and styling the visual elements of a plot are covered in the [Style Mapping](04-Style_Mapping.ipynb) and [Customizing Plots](Customizing_Plots.ipynb) user guides.\n", "\n", "## Working with bokeh directly\n", "\n", "When HoloViews outputs bokeh plots it creates and manipulates bokeh models in the background. If at any time you need access to the underlying Bokeh representation of an object you can use the ``hv.render`` function to convert it. For example let us convert a HoloViews ``Image`` to a bokeh Figure, which will let us access and modify every aspect of the plot:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "img = hv.Image(np.random.rand(10, 10))\n", "\n", "fig = hv.render(img)\n", "\n", "print('Figure: ', fig)\n", "print('Renderers: ', fig.renderers[-1].glyph)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Exporting static files\n", "\n", "Bokeh supports static export to png's using ``Selenium``, ``PhantomJS`` and ``pillow``, to install the required dependencies run:\n", "\n", "```\n", "conda install selenium phantomjs pillow\n", "```\n", "\n", "alternatively install PhantomJS from npm using:\n", "\n", "```\n", "npm install -g phantomjs-prebuilt\n", "```\n", "\n", "To switch to png output persistently you can run:\n", "\n", "```\n", "hv.output(fig='png')\n", "```" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "violin = hv.Violin(np.random.randn(100))\n", "\n", "hv.output(violin, fig='png')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The exported png can also be saved to disk using the ``save`` function by changing the file extension from ``.html``, which exports an interactive plot, ``.png``:\n", "\n", "```python\n", "hv.save(violin, 'violin.png')\n", "```" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Element Style options\n", "\n", "One of the major benefits of bokeh is that it was designed from the ground up with consistency in mind, therefore most style options are a combination of the fill, line, and text style options listed below:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from holoviews.plotting.bokeh.styles import (line_properties, fill_properties, text_properties)\n", "print(\"\"\"\n", "Line properties: %s\\n\n", "Fill properties: %s\\n\n", "Text properties: %s\n", "\"\"\" % (line_properties, fill_properties, text_properties))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Note also that most of these options support vectorized style mapping as described in the [Style Mapping user guide](04-Style_Mapping.ipynb). Here's an example of HoloViews Elements using a Bokeh backend, with bokeh's style options:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "curve_opts = opts.Curve(line_width=10, line_color='indianred', line_dash='dotted', line_alpha=0.5)\n", "point_opts = opts.Points(fill_color='#00AA00', fill_alpha=0.5, line_width=1, line_color='black', size=5)\n", "text_opts = opts.Text(text_align='center', text_baseline='middle', text_color='gray', text_font='Arial')\n", "\n", "xs = np.linspace(0, np.pi*4, 100)\n", "data = (xs, np.sin(xs))\n", "\n", "(hv.Curve(data) + hv.Points(data) + hv.Text(6, 0, 'Here is some text')).opts(\n", " curve_opts, point_opts, text_opts)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Notice that because the first two plots use the same underlying data, they become linked, such that zooming or panning one of the plots makes the corresponding change on the other." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Setting Backend Opts\n", "\n", "HoloViews does not expose every single option from Bokeh.\n", "\n", "Instead, HoloViews allow users to attach [hooks](Customizing_Plots.ipynb#plot-hooks) to modify the plot object directly--but writing these hooks could be cumbersome, especially if it's only used for a single line of update.\n", "\n", "Fortunately, HoloViews allows `backend_opts` for the Bokeh backend to configure options by declaring a dictionary with accessor specification for updating the plot components.\n", "\n", "For example, here's how to make the toolbar auto-hide." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "hv.Curve(data).opts(\n", " backend_opts={\"plot.toolbar.autohide\": True}\n", ")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The following is the equivalent, as a hook." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def hook(hv_plot, element):\n", " toolbar = hv_plot.handles['plot'].toolbar\n", " toolbar.autohide = True\n", "\n", "hv.Curve(data).opts(hooks=[hook])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Notice how much more concise it is with `backend_opts`!\n", "\n", "With knowledge of the attributes of Bokeh, it's possible to configure many other plot components besides `toolbar`. Some examples include `legend`, `colorbar`, `xaxis`, `yaxis`, and much, much more.\n", "\n", "If you're unsure, simply input your best guess and it'll try to provide a list of suggestions if there's an issue." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Sizing Elements\n", "\n", "In the bokeh backend the sizing of plots and specifically layouts of plots is determined in an inside-out or compositional manner. Each subplot can be sized independently and it will fill the allocated space. The sizing is determined by the combination of width, height, aspect and responsive options. In this section we will discover the different approaches to setting plot dimensions and aspects. \n", "\n", "### Width and height\n", "\n", "The most straightforward approach to specifying the size of a plot is using a width and height specified in pixels. This is the default behavior and makes it easy to achieve precise alignment between plots but does not allow for keeping a constant aspect or responsive resizing. In particular, the specified size includes the axes and any legends or colorbars." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "points_a = hv.Points(data)\n", "points_b = hv.Points(data)\n", "\n", "points_a.opts(width=300, height=300) + points_b.opts(width=600, height=300)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Frame width and height\n", "\n", "The frame width on the other hand provides precise control over the inner dimensions of a plot, it ensures the actual plot frame matches the specified dimensions exactly. This makes it possible to achieve a precise aspect ratio between the axis scales, without worrying about the size of axes, colorbars, titles and legends, e.g. below we can see two plots defined using explicit ``frame_width`` and ``frame_height`` share the same dimensions despite the fact that one has a colorbar." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "xs = ys = np.arange(10)\n", "yy, xx = np.meshgrid(xs, ys)\n", "zz = xx*yy\n", "\n", "img = hv.Image(np.random.rand(100, 100))\n", "\n", "points_a.opts(frame_width=200, frame_height=200) +\\\n", "img.opts(frame_width=200, frame_height=200, colorbar=True, axiswise=True)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Aspect\n", "\n", "The ``aspect`` and ``data_aspect`` options provide control over the scaling of the plot dimensions and the axis limits.\n", "\n", "#### ``aspect``:\n", "\n", "The ``aspect`` specifies the ratio between the width and height dimensions of the plot. If specified this options takes absolute precedence over the dimensions of the plot but has no effect on the plot's axis limits. It supports the following options:\n", "\n", "* **``float``** : A numeric value will scale the ratio of plot width to plot height\n", "* **``\"equal\"``** : Sets aspect of the axis scaling to be equal, equivalent to **``data_aspect=1``**\n", "* **``\"square\"``** : Ensures the plot dimensions are square.\n", "\n", "#### ``data_aspect``:\n", "\n", "The ``data_aspect`` specifies the scaling between the x- and y-axis ranges. If specified this option will scale both the plot ranges and dimensions unless explicit ``aspect``, ``width`` or ``height`` value overrides the plot dimensions:\n", "\n", "* **``float``** : Sets ratio between the units on the x-scale and the y-scale" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "xs = np.linspace(0, 10)\n", "ys = np.linspace(0, 5)\n", "\n", "img = hv.Image((xs, ys, xs[:, np.newaxis]*np.sin(ys*4)))\n", "\n", "(img.options(aspect='equal').relabel('aspect=\\'equal\\'') +\n", " img.options(aspect='square', colorbar=True, frame_width=300).relabel('aspect=\\'square\\'') +\n", " img.options(aspect=2).relabel('aspect=2') + \n", " img.options(data_aspect=2, frame_width=300).relabel('data_aspect=2')).cols(2)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Navigable Bounds\n", "\n", "Users may set the `apply_hard_bounds` option to constrain the navigable range (extent one could zoom or pan to). If `True`, the navigable bounds of the plot will be constrained to the range of the data. Go ahead and try to zoom in a out in the plot below, you should find that you cannot zoom beyond the extents of the data.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "x_values = np.linspace(0, 10, 100)\n", "y_values = np.sin(x_values)\n", "\n", "hv.Curve((x_values, y_values)).opts(apply_hard_bounds=True)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "If `xlim` or `ylim` is set for an element, the navigable bounds of the plot will be set based\n", "on the combined extremes of extents between the data and xlim/ylim ranges. In the plot below, the `xlim` constrains the initial view, but you should be able to pan to the x-range between 0 and 12 - the combined extremes of ranges between the data (0,10) and `xlim` (2,12)." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "x_values = np.linspace(0, 10, 100)\n", "y_values = np.sin(x_values)\n", "\n", "hv.Curve((x_values, y_values)).opts(\n", " apply_hard_bounds=True,\n", " xlim=(2, 12),\n", " )" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "If a dimension range is specified (e.g. with `.redim.range`), this range will be used as the hard bounds, regardless of the data range or xlim/ylim. This is because the dimension range is itended to be an override on the minimum and maximum allowable values for the dimension. Read more in [Annotating your Data](./01-Annotating_Data.ipynb)." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "x_values = np.linspace(0, 10, 100)\n", "y_values = np.sin(x_values)\n", "\n", "hv.Curve((x_values, y_values)).opts(\n", " apply_hard_bounds=True,\n", ").redim.range(x=(4, 6))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In the plot above, you should not be able to navigate beyond the specified dimension ranges of `x` (4, 6). " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Responsive\n", "\n", "Since bokeh plots are rendered within a browser window which can be resized dynamically it supports responsive sizing modes allowing the plot to rescale when the window it is placed in is changed. If enabled, the behavior of ``responsive`` modes depends on whether an aspect or width/height option is set. Specifically responsive mode will only work if at least one dimension of the plot is left undefined, e.g. when width and height or width and aspect are set the plot is set to a fixed size, ignoring any ``responsive`` option. This leaves four different ``responsive`` modes:\n", "\n", "* **``scale_both``**: If neither a width or a height are defined but a fixed aspect is defined both axes will be scaled up to the maximum size of the container. Scaling ensures that the aspect ratio of the plot is maintained.\n", "* **``stretch_both``**: If neither a width, height or aspect are defined the plot will stretch to fill all available space.\n", "* **``stretch_width``**: If a height but neither a width or aspect are defined the plot will stretch to fill all available horizontal space.\n", "* **``stretch_height``**: If a width but neither a height or aspect are defined the plot will stretch to fill all available vertical space.\n", "\n", "**Note**: In the notebook stretching and scaling the height does not increase the size of a cell.\n", "\n", "As a simple example let us declare a plot that has a fixed height but stretches to fit all available horizontal space:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "hv.Points(data).opts(height=200, responsive=True, title='stretch width')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Similarly if we declare a fixed ``aspect`` or ``data_aspect`` responsive modes will try to fill all available space but avoid distorting the specified aspect:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "img.opts(data_aspect=0.5, responsive=True, title='scale both')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Alignment\n", "\n", "The alignment of a plot in a row or column can be controlled using the ``align`` option. It controls both the vertical alignment in a row and the horizontal alignment in a column and can be set to one of `'start'`, `'center'` or `'end'` (where `'start'` is the default)." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Vertical" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "points = hv.Points(data).opts(axiswise=True)\n", "img = hv.Image((xs, ys, xs[:, np.newaxis]*np.sin(ys*4)))\n", "\n", "img + points.opts(height=200, align='end')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Horizontal" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "(img.opts(axiswise=True, width=200, align='center') + points).cols(1)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Grid lines" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Grid lines can be controlled through the combination of ``show_grid`` and ``gridstyle`` parameters. The ``gridstyle`` allows specifying a number of options including:\n", "\n", "* ``grid_line_color``\n", "* ``grid_line_alpha``\n", "* ``grid_line_dash``\n", "* ``grid_line_width``\n", "* ``grid_bounds``\n", "* ``grid_band``\n", "\n", "These options may also be applied to minor grid lines by prepending the ``'minor_'`` prefix and may be applied to a specific axis by replacing ``'grid_`` with ``'xgrid_'`` or ``'ygrid_'``. Here we combine some of these options to generate a complex grid pattern:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "grid_style = {'grid_line_color': 'black', 'grid_line_width': 1.5, 'ygrid_bounds': (0.3, 0.7),\n", " 'minor_xgrid_line_color': 'lightgray', 'xgrid_line_dash': [4, 4]}\n", "\n", "hv.Points(np.random.rand(10, 2)).opts(gridstyle=grid_style, show_grid=True, size=5, width=600)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Containers\n", "\n", "The bokeh plotting extension also supports a number of additional features relating to container components." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Tabs" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Using bokeh, both ``(Nd)Overlay`` and ``(Nd)Layout`` types may be displayed inside a ``tabs`` widget. This may be enabled via a plot option ``tabs``, and may even be nested inside a Layout." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "x,y = np.mgrid[-50:51, -50:51] * 0.1\n", "\n", "img = hv.Image(np.sin(x**2+y**2), bounds=(-1,-1,1,1))\n", "(img.relabel('Image') * img.sample(x=0).relabel('Cross-section')).opts(tabs=True)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Another reason to use ``tabs`` is that some Layout combinations may not be able to be displayed directly using HoloViews. For example, it is not currently possible to display a ``GridSpace`` as part of a ``Layout`` in any backend, and this combination will automatically switch to a ``tab`` representation for the bokeh backend." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Interactive Legends\n", "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "When using ``NdOverlay`` and ``Overlay`` containers each element will get a legend entry, which can be used to interactively toggle the visibility of the element. In this example we will create a number of ``Histogram`` elements each with a different mean. By setting a ``muted_fill_alpha`` we can define the style of the element when it is de-selected using the legend, simply try tapping on each legend entry to see the effect:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "hv.NdOverlay({i: hv.Histogram(np.histogram(np.random.randn(100)+i*2)) for i in range(5)}).opts(\n", " 'Histogram', width=600, alpha=0.8, muted_fill_alpha=0.1)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The other ``muted_`` options can be used to define other aspects of the Histogram style when it is unselected.\n", "\n", "If you have multiple plots in a ``Layout`` with the same legend label, muting one of them will automatically mute all of them. " ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "overlay1 = hv.Curve([0, 0], label=\"A\") * hv.Curve([1, 1], label=\"B\")\n", "overlay2 = hv.Curve([2, 2], label=\"A\") * hv.Curve([3, 3], label=\"B\")\n", "layout = overlay1 + overlay2\n", "layout " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "If you want to turn off this behavior, use ``.opts(sync_legends=False)``" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "layout.opts(sync_legends=False)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "If you want to control the number of legend shown in the ``Layout`` or the position of them ``show_legends`` and ``legend_position`` can be used." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "layout.opts(sync_legends=True, show_legends=0, legend_position=\"top_left\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Marginals\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The Bokeh backend also supports marginal plots to generate adjoined plots. The most convenient way to build an AdjointLayout is with the ``.hist()`` method." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "points = hv.Points(np.random.randn(500,2))\n", "points.hist(num_bins=51, dimension=['x','y'])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "When the histogram represents a quantity that is mapped to a value dimension with a corresponding colormap, it will automatically share the colormap, making it useful as a colorbar for that dimension as well as a histogram." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "img.hist(num_bins=100, dimension=['x', 'y'], weight_dimension='z', mean_weighted=True) +\\\n", "img.hist(dimension='z')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Tools\n", "\n", "Bokeh provides a range of tools to interact with a plot and HoloViews adds a number of tools by default but also makes it easy to add additional tools. The ``default_tools`` define the list of tools that are added automatically and usually a user would override only the ``tools`` option to add additional tools. By default the ``default_tools`` include:\n", "\n", " ['save', 'pan', 'wheel_zoom', 'box_zoom', 'reset']" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Toolbar\n", "\n", "The bokeh toolbar is added automatically and will be placed to the right for a single plot and on the top for a layout. Additionally for layouts of plots it will automatically merge the toolbars to avoid crowding the plot. However both behaviors can be customized, the toolbar can be hidden or moved to a different location on a plot by setting the ``toolbar`` option to one of:\n", "\n", " ['above', 'below', 'left', 'right', 'disable', None]\n", "\n", "Secondly a layout or grid plot supports the ``merge_tools`` option which can be used to maintain one toolbar per plot:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "(hv.Curve([1, 2, 3]).opts(toolbar='above') + hv.Curve([1, 2, 3]).opts(toolbar=None)).opts(merge_tools=False)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Hover tools" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Some Elements allow revealing additional data by hovering over the data. To enable the hover tool, simply supply ``'hover'`` as a list to the ``tools`` plot option. By default the tool will display information for all the dimensions specified on the element:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "error = np.random.rand(100, 3)\n", "heatmap_data = {(chr(65+i), chr(97+j)):i*j for i in range(5) for j in range(5) if i!=j}\n", "data = [np.random.normal() for i in range(10000)]\n", "hist = np.histogram(data, 20)\n", "\n", "points = hv.Points(error)\n", "heatmap = hv.HeatMap(heatmap_data).sort()\n", "histogram = hv.Histogram(hist)\n", "image = hv.Image(np.random.rand(50,50))\n", "\n", "(points + heatmap + histogram + image).opts(\n", " opts.Points(tools=['hover'], size=5), opts.HeatMap(tools=['hover']),\n", " opts.Image(tools=['hover']), opts.Histogram(tools=['hover']),\n", " opts.Layout(shared_axes=False)).cols(2)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Moreover, you can provide `'vline'`, the equivalent of passing `HoverTool(mode='vline')`, or `'hline'` to set the hit-testing behavior." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "hv.Curve(np.arange(100)).opts(tools=[\"vline\"]) + hv.Curve(np.arange(100)).opts(tools=[\"hline\"])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Equivalently, you may say `tools=[\"hover\"]` alongside `hover_mode`." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "(\n", " hv.Curve(np.arange(100)).opts(tools=[\"hover\"], hover_mode=\"vline\")\n", " + hv.Curve(np.arange(100)).opts(tools=[\"hover\"], hover_mode=\"hline\")\n", ")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "If you'd like finer control on the formatting, you may use `hover_tooltips` to declare the tooltips as a list of tuples of the labels and a specification of the dimension name and how to display it.\n", "\n", "Behind the scenes, the `hover_tooltips` feature extends the capabilities of Bokeh's `HoverTool` tooltips by providing additional flexibility and customization options, so for a reference see the [bokeh user guide](https://bokeh.pydata.org/en/latest/docs/user_guide/tools.html#hovertool)." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "hover_tooltips = [\n", " ('Name', '@name'),\n", " ('Symbol', '@symbol'),\n", " ('CPK', '$color[hex, swatch]:CPK')\n", "]\n", "\n", "points.clone().opts(\n", " tools=[\"hover\"], hover_tooltips=hover_tooltips, color='metal', cmap='Category20',\n", " line_color='black', size=dim('atomic radius')/10,\n", " width=600, height=400, show_grid=True,\n", " title='Chemical Elements by Type (scaled by atomic radius)')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Unique from Bokeh's `HoverTool`, the HoloViews' `hover_tooltips` also supports a mix of string and tuple formats for defining tooltips, allowing for both direct references to data columns and customized display options.\n", "\n", "Additionally, you can include as many, or as little, dimension names as desired." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "hover_tooltips = [\n", " \"name\", # will assume @name\n", " (\"Symbol\", \"@symbol\"), # @ still required if tuple\n", " ('CPK', '$color[hex, swatch]:CPK'),\n", " \"density\"\n", "]\n", "\n", "points.clone().opts(\n", " tools=[\"hover\"], hover_tooltips=hover_tooltips, color='metal', cmap='Category20',\n", " line_color='black', size=dim('atomic radius')/10,\n", " width=600, height=400, show_grid=True,\n", " title='Chemical Elements by Type (scaled by atomic radius)')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "`hover_tooltips` also support displaying the HoloViews element's `label` and `group`.\n", "\n", "Keep in mind, to reference these special variables that are not based on the data, a prefix of `$` is required!" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "a_curve = hv.Curve([0, 1, 2], label=\"A\", group=\"C\")\n", "b_curve = hv.Curve([2, 1, 0], label=\"B\", group=\"C\")\n", "(a_curve * b_curve).opts(\"Curve\", hover_tooltips=[\"$label\", \"$group\", \"@x\", \"y\"]) # $ is required, @ is not needed for string" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "If you need special formatting, you may also specify the formats inside `hover_tooltips` alongside `hover_formatters`." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def datetime(x):\n", " return np.array(x, dtype=np.datetime64)\n", "\n", "\n", "df = pd.DataFrame(\n", " {\n", " \"date\": [\"2019-01-01\", \"2019-01-02\", \"2019-01-03\"],\n", " \"adj_close\": [100, 101, 100000],\n", " }\n", ")\n", "\n", "curve = hv.Curve((datetime(df[\"date\"]), df[\"adj_close\"]), \"date\", \"adj close\")\n", "curve.opts(\n", " hover_tooltips=[\"date\", (\"Close\", \"$@{adj close}{0.2f}\")], # use @{ } for dims with spaces\n", " hover_formatters={\"@{adj close}\": \"printf\"}, # use 'printf' formatter for '@{adj close}' field\n", " hover_mode=\"vline\",\n", ")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You can provide HTML strings too! See a demo [here](../gallery/demos/bokeh/html_hover_tooltips.ipynb), or explicitly declare the columns to display by manually constructing a Bokeh [`HoverTool`](https://bokeh.pydata.org/en/latest/docs/user_guide/tools.html#hovertool)." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from bokeh.models import HoverTool\n", "from bokeh.sampledata.periodic_table import elements\n", "\n", "points = hv.Points(\n", " elements, ['electronegativity', 'density'],\n", " ['name', 'symbol', 'metal', 'CPK', 'atomic radius'],\n", ").sort('metal')\n", "\n", "tooltips = [\n", " ('Name', '@name'),\n", " ('Symbol', '@symbol'),\n", " ('CPK', '$color[hex, swatch]:CPK')\n", "]\n", "hover = HoverTool(tooltips=tooltips)\n", "\n", "points.opts(\n", " tools=[hover], color='metal', cmap='Category20',\n", " line_color='black', size=dim('atomic radius')/10,\n", " width=600, height=400, show_grid=True,\n", " title='Chemical Elements by Type (scaled by atomic radius)')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Selection tools" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Bokeh provides a number of tools for selecting data points including ``tap``, ``box_select``, ``lasso_select`` and ``poly_select``. To distinguish between selected and unselected data points we can also control the color and alpha of the ``selection`` and ``nonselection`` points. You can try out any of these selection tools and see how the plot is affected:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "hv.Points(error).opts(\n", " color='blue', nonselection_color='red', size=10, tools=['box_select', 'lasso_select', 'tap'])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Selection tool with shared axes and linked brushing" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "When dealing with complex multi-variate data it is often useful to explore interactions between variables across plots. HoloViews will automatically link the data sources of plots in a Layout if they draw from the same data, allowing for both linked axes and brushing.\n", "\n", "We'll see what this looks like in practice using a small dataset of macro-economic data:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "macro_df = pd.read_csv('http://assets.holoviews.org/macro.csv', sep='\\t')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "By creating two ``Points`` Elements, which both draw their data from the same pandas DataFrame, the two plots become automatically linked. Note that the [Linking Plots user guide](Linking_Plots.ipynb) provides a more explicit way to declare two elements as being linked without having to share the same underlying datastructure. The automated linking behavior can be toggled with the ``shared_datasource`` plot option on a ``Layout`` or ``GridSpace``. You can try selecting data in one plot, and see how the corresponding data (those on the same rows of the DataFrame, even if the plots show different data, will be highlighted in each. " ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "(hv.Scatter(macro_df, 'year', 'gdp') + hv.Scatter(macro_df, 'gdp', 'unem')).opts(\n", " opts.Scatter(tools=['box_select', 'lasso_select']), opts.Layout(shared_axes=True, shared_datasource=True))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "A gridmatrix is a clear use case for linked plotting. This operation plots any combination of numeric variables against each other, in a grid, and selecting datapoints in any plot will highlight them in all of them. Such linking can thus reveal how values in a particular range (e.g. very large outliers along one dimension) relate to each of the other dimensions." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "table = hv.Dataset(macro_df, kdims=['year', 'country'])\n", "matrix = hv.operation.gridmatrix(table.groupby('country'))\n", "\n", "matrix.select(country=['West Germany', 'United Kingdom', 'United States']).opts(\n", " opts.Scatter(tools=['box_select', 'lasso_select', 'hover'], border=0))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Drawing Tools\n", "\n", "Another commonly useful set of tools are the drawing tools which are integrated with the linked streams introduced in the [Custom Interactivity guide](13-Custom_Interactivity.ipynb). These tools allow drawing and annotating a plot and accessing the annotation back in Python. The available drawing tools include:\n", "\n", "* [PointDraw](../reference/streams/bokeh/PointDraw.ipynb): The ``PointDraw`` stream adds a bokeh tool to the source plot, which allows drawing, dragging and deleting points.\n", "* [BoxEdit](../reference/streams/bokeh/BoxEdit.ipynb): The ``BoxEdit`` stream adds a bokeh tool to the source plot, which allows drawing, dragging and deleting boxes.\n", "* [FreehandDraw](../reference/streams/bokeh/FreehandDraw.ipynb): The ``FreehandDraw`` stream adds a bokeh tool to the source plot, which allows freehand drawing on the plot canvas\n", "* [PolyDraw](../reference/streams/bokeh/PolyDraw.ipynb): The ``PolyDraw`` stream adds a bokeh tool to the source plot, which allows drawing, dragging and deleting polygons and paths.\n", "* [PolyEdit](../reference/streams/bokeh/PolyEdit.ipynb): The ``PolyEdit`` stream adds a bokeh tool to the source plot, which allows drawing, dragging and deleting vertices on polygons and paths.\n", "\n", "Each of the reference notebooks explains the tools in more detail but to get an of how these tools work see the ``FreehandDraw`` example below, which allows drawing on the canvas and accessing the drawn data from Python:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "path = hv.Path([])\n", "freehand = hv.streams.FreehandDraw(source=path, num_objects=3)\n", "\n", "path.opts(\n", " opts.Path(active_tools=['freehand_draw'], height=400, line_width=10, width=400))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "To access the data from Python, you can access the ``element`` property on the stream, which lets us access each drawn line drawn as a separate ``Path`` element:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "freehand.element.split()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The [Reference Gallery](http://holoviews.org/reference/index.html) shows examples of all the Elements supported for Bokeh, in a format that can be compared with the corresponding matplotlib versions." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Theming\n", "\n", "Bokeh supports theming via the [Theme object](https://bokeh.pydata.org/en/latest/docs/reference/themes.html) object which can also be using in HoloViews. Applying a Bokeh theme is useful when you need to set detailed aesthetic options not directly exposed via the HoloViews style options.\n", "\n", "To apply a Bokeh theme, you will need to create a ``Theme`` object:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from bokeh.themes.theme import Theme\n", "\n", "theme = Theme(\n", " json={\n", " 'attrs' : {\n", " 'Figure' : {\n", " 'background_fill_color': '#2F2F2F',\n", " 'border_fill_color': '#2F2F2F',\n", " 'outline_line_color': '#444444',\n", " },\n", " 'Grid': {\n", " 'grid_line_dash': [6, 4],\n", " 'grid_line_alpha': .3,\n", " },\n", "\n", " 'Axis': {\n", " 'major_label_text_color': 'white',\n", " 'axis_label_text_color': 'white',\n", " 'major_tick_line_color': 'white',\n", " 'minor_tick_line_color': 'white',\n", " 'axis_line_color': \"white\"\n", " }\n", " }\n", "})" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Instead of supplying a JSON object, you can also create a Bokeh ``Theme`` object from a [YAML file](https://bokeh.pydata.org/en/latest/docs/reference/themes.html). Once the ``Theme`` object is created, you can apply it by setting it on the ``theme`` parameter of the current Bokeh renderer:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "hv.renderer('bokeh').theme = theme" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The theme will then be applied to subsequent plots:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "xs = np.linspace(0, np.pi*4, 100)\n", "hv.Curve((xs, np.sin(xs)), label='foo').opts(bgcolor='grey')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You may also supply a name from Bokeh's built-in-themes:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "hv.renderer('bokeh').theme = 'light_minimal'\n", "xs = np.linspace(0, np.pi*4, 100)\n", "hv.Curve((xs, np.sin(xs)), label='foo')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "To disable theming, you can set the ``theme`` parameter on the Bokeh renderer to ``None``." ] } ], "metadata": { "language_info": { "name": "python", "pygments_lexer": "ipython3" } }, "nbformat": 4, "nbformat_minor": 4 }