{ "cells": [ { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import numpy as np\n", "import holoviews as hv\n", "hv.extension('bokeh', 'matplotlib')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Since HoloViews supports a number of rendering backends, some of the styling options will differ between them. However, some fundamental concepts such as color cycles, colormapping, setting titles, and controlling legends are shared across backends. In this guide we will review how to apply these common styling options to plots. Once you know how to use these, you should be able to see how to use the options for specific backends covered in the [Plotting with bokeh](./Plotting_with_Bokeh.ipynb) and [Plotting with matplotlib](./Plotting_with_Matplotlib.ipynb) user guides." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Cycles and Palettes\n", "\n", "Frequently we want to plot multiple subsets of data, which is made easy by using ``Overlay`` and ``NdOverlay`` objects. When overlaying multiple elements of the same type they will need to be distinguished visually, and HoloViews provides two mechanisms for styling the different subsets automatically in those cases:\n", "\n", "* ``Cycle``: A Cycle defines a list of discrete styles\n", "* ``Palette``: A Palette defines a continuous color space which will be sampled discretely" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Cycle\n", "\n", "A ``Cycle`` can be applied to any of the style options on an element. By default, most elements define a ``Cycle`` on the color property. Here we will create a overlay of three ``Points`` objects using the default cycles, then display it using the default cycles along with a copy where we changed the dot color and size using a custom ``Cycle``:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "points = (\n", " hv.Points(np.random.randn(50, 2) ) *\n", " hv.Points(np.random.randn(50, 2) + 1 ) *\n", " hv.Points(np.random.randn(50, 2) * 0.5)\n", ")\n", "\n", "color_cycle = hv.Cycle(['red', 'green', 'blue'])\n", "points + points.options({'Points': {'color': color_cycle, 'size': 5}})" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Here color has been changed to cycle over the three provided colors, while size has been specified as a constant (though a cycle like `hv.Cycle([2,5,10])` could just as easily have been used for the size as well).\n", "\n", "#### Defaults\n", "\n", "In addition to defining custom color cycles by explicitly defining a list of colors, ``Cycle`` also defines a list of default Cycles generated from bokeh Palettes and matplotlib colormaps:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def format_list(l):\n", " print(' '.join(sorted([k for k in l if not k.endswith('_r')])))\n", "\n", "format_list(hv.Cycle.default_cycles.keys())" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "(Here some of these Cycles have a reversed variant ending in `_r` that is not shown.)\n", "\n", "To use one of these default Cycles simply construct the Cycle with the corresponding key:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "xs = np.linspace(0, np.pi*2)\n", "curves = hv.Overlay([hv.Curve(np.sin(xs+p)) for p in np.linspace(0, np.pi, 10)])\n", "\n", "curves.options({'Curve': {'color': hv.Cycle('Category20'), 'width': 600}})" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Markers and sizes\n", "\n", "The above examples focus on color Cycles, but Cycles may be used to define any style option. Here let's use them to cycle over a number of marker styles and sizes, which will be expanded by cycling over each item independently. In this case we are cycling over three Cycles, resulting in the following style combinations:\n", "\n", "1. ``{'color': '#30a2da', 'marker': 'x', 'size': 10}``\n", "2. ``{'color': '#fc4f30', 'marker': '^', 'size': 5}``\n", "3. ``{'color': '#e5ae38', 'marker': '+', 'size': 10}``" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "color = hv.Cycle(['#30a2da', '#fc4f30', '#e5ae38'])\n", "markers = hv.Cycle(['x', '^', '+'])\n", "sizes = hv.Cycle([10, 5])\n", "points.options({'Points': {'marker': markers, 'size': sizes}})" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Palettes\n", "\n", "Palettes are similar to cycles, but treat a set of colors as a continuous colorspace to be sampled at regularly spaced intervals. Again they are made automatically available from existing colormaps (with `_r` versions also available):" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "format_list(hv.Palette.colormaps.keys())" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "(Here each colormap `X` has a corresponding version `X_r` with the values reversed; the `_r` variants are suppressed above.)\n", "\n", "As a simple example we will create a Palette from the Spectral colormap and apply it to an Overlay of 6 Ellipses. Comparing it to the Spectral ``Cycle`` we can immediately see that the Palette covers the entire color space spanned by the Spectral colormap, while the Cycle instead uses the first 6 colors of the Spectral colormap:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "ellipses = hv.Overlay([hv.Ellipse(0, 0, s) for s in range(6)])\n", "\n", "ellipses.relabel('Palette').options({'Ellipse': dict(color=hv.Palette('Spectral'), line_width=5)}) +\\\n", "ellipses.relabel('Cycle' ).options({'Ellipse': dict(color=hv.Cycle( 'Spectral'), line_width=5)})" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Thus if you want to have have a discrete set of distinguishable colors starting from a list of colors that vary slowly and continuously, you should usually supply it as a Palette, not a Cycle. Conversely, you should use a Cycle when you want to iterate through a specific list of colors, in order, without skipping around the list like a Palette will.\n", "\n", "\n", "## Colormapping\n", "\n", "Color cycles and styles are useful for categorical plots and when overlaying multiple subsets, but when we want to map data values to a color it is better to use HoloViews' facilities for color mapping. Certain image-like types will apply colormapping automatically; e.g. for ``Image``, ``QuadMesh`` or ``HeatMap`` types the first value dimension is automatically mapped to the color. In other cases the values to colormap can be declared through the ``color_index``, which may reference any dimension by name or by numerical index.\n", "\n", "\n", "#### Named colormaps\n", "\n", "HoloViews accepts colormaps specified either as an explicit list of hex or HTML colors, as a Matplotlib colormap object, or as the name of a bokeh, matplotlib, and colorcet palettes/colormap (which are available when the respective library is imported). The named colormaps available are listed here (suppressing the `_r` versions) and illustrated in detail in the separate [Colormaps](Colormaps.ipynb) user guide:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "format_list(hv.plotting.list_cmaps())" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "To use one of these colormaps simply refer to it by name with the ``cmap`` style option:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "ls = np.linspace(0, 10, 400)\n", "xx, yy = np.meshgrid(ls, ls)\n", "bounds=(-1,-1,1,1) # Coordinate system: (left, bottom, top, right)\n", "img = hv.Image(np.sin(xx)*np.cos(yy), bounds=bounds).options(colorbar=True, width=400)\n", "\n", "img.options(cmap='PiYG') + img.options(cmap='PiYG_r')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "##### Custom colormaps\n", "\n", "You can make your own custom colormaps by providing a list of hex colors:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "img.options(cmap=['#0000ff', '#8888ff', '#ffffff', '#ff8888', '#ff0000'], colorbar=True, width=400)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "##### Discrete color levels" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Lastly, existing colormaps can be made discrete by defining an integer number of ``color_levels``:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "img.options(cmap='PiYG', color_levels=5) + img.options(cmap='PiYG', color_levels=11) " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Setting color ranges\n", "\n", "For an image-like element, color ranges are determined by the range of the `z` value dimension, and they can thus be controlled using the ``.redim.range`` method with `z`. As an example, let's set some values in the image array to NaN and then set the range to clip the data at 0 and 0.9. By declaring the ``clipping_colors`` option we can control what colors are used for NaN values and for values above and below the defined range:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "clipping = {'min': 'red', 'max': 'green', 'NaN': 'gray'}\n", "opts = dict(cmap='Blues', colorbar=True, width=300, height=230, axiswise=True)\n", "\n", "arr = np.sin(xx)*np.cos(yy)\n", "arr[:190, :127] = np.NaN\n", "\n", "original = hv.Image(arr, bounds=bounds).options(**opts)\n", "colored = original.options(clipping_colors=clipping)\n", "clipped = colored.redim.range(z=(0, 0.9))\n", "\n", "original + colored + clipped" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "By default (left plot above), the min and max values in the array map to the first color (white) and last color (dark blue) in the colormap, and NaNs are ``'transparent'`` (an RGBA tuple of (0, 0, 0, 0)), revealing the underlying plot background. When the specified `clipping_colors` are supplied (middle plot above), NaN values are now colored gray, but the plot is otherwise the same because the autoranging still ensures that no value is mapped outside the available color range. Finally, when the `z` range is reduced (right plot above), the color range is mapped from a different range of numerical `z` values, and some values now fall outside the range and are thus clipped to red or green as specified.\n", " \n", " \n", " #### Other options\n", "\n", "* ``logz``: Enable logarithmic color scale (e.g. ``logz=True``)\n", "* ``symmetric``: Ensures that the color scale is centered on zero (e.g. ``symmetric=True``)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Using color_index\n", "\n", "As mentioned above, when plotting elements that do not automatically map colors to certain dimensions, we can use the ``color_index`` option to do so explicitly. This allows colormapping both continuously valued and categorical values.\n", "\n", "#### Continuous values\n", "\n", "If we provide a continuous value for the ``color_index``, we have a continuous colormap and can enable a ``colorbar``:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "polygons = hv.Polygons([{('x', 'y'): hv.Ellipse(0, 0, (i, i)).array(), 'z': i} for i in range(1, 10)[::-1]], vdims='z')\n", "\n", "polygons.options(color_index='z', colorbar=True, width=380)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Categorical values" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Conversely, when mapping a categorical value into a set of colors, we automatically get a legend (which can be disabled using the ``show_legend`` option):" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "categorical_points = hv.Points((np.random.rand(100), \n", " np.random.rand(100), \n", " np.random.choice(list('ABCD'), 100)), vdims='Category')\n", "\n", "categorical_points.sort('Category').options(color_index='Category', cmap='Category20', size=5)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Explicit color mapping\n", "\n", "Instead of using a listed colormap, you can provide an explicit mapping from category to color. Here we will map the categories 'A', 'B', 'C' and 'D' to specific colors:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "explicit_mapping = {'A': 'blue', 'B': 'red', 'C': 'green', 'D': 'purple'}\n", "\n", "categorical_points.sort('Category').options(color_index='Category', cmap=explicit_mapping, size=5)" ] } ], "metadata": { "language_info": { "name": "python", "pygments_lexer": "ipython3" } }, "nbformat": 4, "nbformat_minor": 2 }