{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Working with large data using Datashader\n",
    "\n",
    "The various plotting-library backends supported by HoloViews, such as Matplotlib, Bokeh, and Plotly, each have limitations on the amount of data that is practical to work with.  Bokeh and Plotly in particular mirror your data directly into an HTML page viewable in your browser, which can cause problems when data sizes approach the limited memory available for each web page in current browsers.\n",
    "\n",
    "Luckily, a visualization of even the largest dataset will be constrained by the resolution of your display device, and so one approach to handling such data is to pre-render or rasterize the data into a fixed-size array or image *before* sending it to the backend plotting library and thus to your local web browser. The [Datashader](https://github.com/bokeh/datashader) library provides a high-performance big-data server-side rasterization pipeline that works seamlessly with HoloViews to support datasets that are orders of magnitude larger than those supported natively by the plotting-library backends, including millions or billions of points even on ordinary laptops.\n",
    "\n",
    "Here, we will see how and when to use Datashader with HoloViews Elements and Containers. For simplicity in this discussion we'll focus on simple synthetic datasets, but [Datashader's examples](http://datashader.org/topics) include a wide variety of real datasets that give a much better idea of the power of using Datashader with HoloViews, and [HoloViz.org](http://holoviz.org) shows how to install and work with HoloViews and Datashader together.\n",
    "\n",
    "<style>.container { width:100% !important; }</style>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import datashader as ds\n",
    "import numpy as np\n",
    "import holoviews as hv\n",
    "import pandas as pd\n",
    "import numpy as np\n",
    "\n",
    "from holoviews import opts\n",
    "from holoviews.operation.datashader import datashade, rasterize, shade, dynspread, spread\n",
    "from holoviews.operation.resample import ResampleOperation2D\n",
    "from holoviews.operation import decimate\n",
    "\n",
    "hv.extension('bokeh','matplotlib', width=100)\n",
    "\n",
    "# Default values suitable for this notebook\n",
    "decimate.max_samples=1000\n",
    "dynspread.max_px=20\n",
    "dynspread.threshold=0.5\n",
    "ResampleOperation2D.width=500\n",
    "ResampleOperation2D.height=500\n",
    "\n",
    "def random_walk(n, f=5000):\n",
    "    \"\"\"Random walk in a 2D space, smoothed with a filter of length f\"\"\"\n",
    "    xs = np.convolve(np.random.normal(0, 0.1, size=n), np.ones(f)/f).cumsum()\n",
    "    ys = np.convolve(np.random.normal(0, 0.1, size=n), np.ones(f)/f).cumsum()\n",
    "    xs += 0.1*np.sin(0.1*np.array(range(n-1+f))) # add wobble on x axis\n",
    "    xs += np.random.normal(0, 0.005, size=n-1+f) # add measurement noise\n",
    "    ys += np.random.normal(0, 0.005, size=n-1+f)\n",
    "    return np.column_stack([xs, ys])\n",
    "\n",
    "def random_cov():\n",
    "    \"\"\"Random covariance for use in generating 2D Gaussian distributions\"\"\"\n",
    "    A = np.random.randn(2,2)\n",
    "    return np.dot(A, A.T)\n",
    "\n",
    "def time_series(T = 1, N = 100, mu = 0.1, sigma = 0.1, S0 = 20):  \n",
    "    \"\"\"Parameterized noisy time series\"\"\"\n",
    "    dt = float(T)/N\n",
    "    t = np.linspace(0, T, N)\n",
    "    W = np.random.standard_normal(size = N) \n",
    "    W = np.cumsum(W)*np.sqrt(dt) # standard brownian motion\n",
    "    X = (mu-0.5*sigma**2)*t + sigma*W \n",
    "    S = S0*np.exp(X) # geometric brownian motion\n",
    "    return S"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<center><div class=\"alert alert-info\" role=\"alert\">This notebook makes use of dynamic updates, which require a running a live Jupyter or Bokeh server.<br>\n",
    "When viewed statically, the plots will not update fully when you zoom and pan.<br></div></center>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Principles of datashading\n",
    "\n",
    "Because HoloViews elements are fundamentally data containers, not visualizations, you can very quickly declare elements such as ``Points`` or ``Path`` containing datasets that may be as large as the full memory available on your machine (or even larger if using Dask dataframes). So even for very large datasets, you can easily  specify a data structure that you can work with for making selections, sampling, aggregations, and so on. However, as soon as you try to visualize it directly with either the Matplotlib, Plotly, or Bokeh plotting extensions, the rendering process may be prohibitively expensive.\n",
    "\n",
    "Let's start with a simple example that's easy to visualize in any plotting library:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "np.random.seed(1)\n",
    "points = hv.Points(np.random.multivariate_normal((0,0), [[0.1, 0.1], [0.1, 1.0]], (1000,)),label=\"Points\")\n",
    "paths = hv.Path([random_walk(2000,30)], kdims=[\"u\",\"v\"], label=\"Paths\")\n",
    "\n",
    "points + paths"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "These browser-based plots are fully interactive, as you can see if you select the Wheel Zoom or Box Zoom tools and use your scroll wheel or click and drag.  \n",
    "\n",
    "Because all of the data in these plots gets transferred directly into the web browser, the interactive functionality will be available even on a static export of this figure as a web page. Note that even though the visualization above is not computationally expensive, even with just 1000 points as in the scatterplot above, the plot already suffers from [overplotting](https://anaconda.org/jbednar/plotting_pitfalls), with later points obscuring previously plotted points.  \n",
    "\n",
    "With much larger datasets, these issues will quickly make it impossible to see the true structure of the data.  We can easily declare 50X or 1000X larger versions of the same plots above, but if we tried to visualize them directly they would be unusably slow even if the browser did not crash:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "np.random.seed(1)\n",
    "points = hv.Points(np.random.multivariate_normal((0,0), [[0.1, 0.1], [0.1, 1.0]], (1000000,)),label=\"Points\")\n",
    "paths = hv.Path([0.15*random_walk(100000) for i in range(10)], kdims=[\"u\",\"v\"], label=\"Paths\")\n",
    "\n",
    "#points + paths  ## Danger! Browsers can't handle 1 million points!"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Luckily, HoloViews Elements are just containers for data and associated metadata, not plots, so HoloViews can generate entirely different types of visualizations from the same data structure when appropriate.  For instance, in the plot on the left below you can see the result of applying a `decimate()` operation acting on the `points` object, which will automatically downsample this million-point dataset to at most 1000 points at any time as you zoom in or out:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "decimate( points).relabel(\"Decimated Points\") + \\\n",
    "rasterize(points).relabel(\"Rasterized Points\").opts(colorbar=True, width=350) + \\\n",
    "rasterize(paths ).relabel(\"Rasterized Paths\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Decimating a plot in this way can be useful, but it discards most of the data even while still suffering from overplotting. \n",
    "\n",
    "If you have Datashader installed, you can instead use Datashader operations like `rasterize()` to create a dynamic Datashader-based Bokeh plot. The middle plot above shows the result of using `rasterize()` to create a dynamic Datashader-based plot out of an Element with arbitrarily large data. In the rasterized version, the data is binned into a fixed-size 2D array automatically on every zoom or pan event, revealing all the data available at that zoom level and avoiding issues with overplotting by dynamically rescaling the colors used. Each pixel is colored by how many datapoints fall in that pixel, faithfully revealing the data's distribution in a easy-to-display plot. The colorbar indicates the number of points indicated by that color, up to 300 or so for the pixels with the most points here. The same process is used for the line-based data in the Paths plot, where darker colors represent path intersections.\n",
    "\n",
    "These two Datashader-based plots are similar to the native Bokeh plots above, but instead of making a static Bokeh plot that embeds points or line segments directly into the browser, HoloViews sets up a Bokeh plot with dynamic callbacks instructing Datashader to rasterize the data into a fixed-size array (effectively a 2D histogram) instead. The dynamic re-rendering provides an interactive user experience, even though the data itself is never provided directly to the browser. Of course, because the full data is not in the browser, a static export of this page (e.g. on holoviews.org or on anaconda.org) will only show the initially rendered version, and will not update with new rasterized arrays when zooming as it will when there is a live Python process available.\n",
    "\n",
    "Though you can no longer have a completely interactive exported file, with the Datashader version on a live server you can now change the number of data points from 1000000 to 10000000 or more to see how well your machine will handle larger datasets. It will get a bit slower, but if you have enough memory, it should still be very usable, and should never crash your browser like transferring the whole dataset into your browser would.  If you don't have enough memory, you can instead set up a [Dask](http://dask.pydata.org) dataframe as shown in other Datashader examples, which will provide out-of-core and/or distributed processing to handle even the largest datasets if you have enough computational power and memory or are willing to wait for out-of-core computation."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# HoloViews operations for datashading\n",
    "\n",
    "HoloViews provides several operations for calling Datashader on HoloViews elements, including `rasterize()`, `shade()`, and `datashade()`.\n",
    "\n",
    "`rasterize()` uses Datashader to render the data into what is by default a 2D histogram, where every array cell counts the data points falling into that pixel. Bokeh then colormaps that array, turning each cell into a pixel in an image. \n",
    "\n",
    "Instead of having Bokeh do the colormapping, you can instruct Datashader to do so, by wrapping the output of `rasterize()` in a call to `shade()`, where `shade()` is Datashader's colormapping function. The `datashade()` operation is also provided as a simple macro, where `datashade(x)` is equivalent to `shade(rasterize(x))`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "ropts = dict(colorbar=True, tools=[\"hover\"], width=350)\n",
    "\n",
    "rasterize(      points).opts(cmap=\"kbc_r\", cnorm=\"linear\").relabel('rasterize()').opts(**ropts).hist() + \\\n",
    "shade(rasterize(points),     cmap=\"kbc_r\", cnorm=\"linear\").relabel(\"shade(rasterize())\") + \\\n",
    "datashade(      points,      cmap=\"kbc_r\", cnorm=\"linear\").relabel(\"datashade()\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In all three of the above plots, `rasterize()` is being called to aggregate the data (a large set of x,y locations) into a rectangular grid, with each grid cell counting up the number of points that fall into it.  In the first plot, only `rasterize()` is done, and the resulting numeric array of counts is passed to Bokeh for colormapping. That way hover and colorbars can be supported (as shown), and Bokeh can then provide dynamic (client-side, browser-based) colormapping tools in JavaScript, allowing users to have dynamic control over even static HTML plots.  For instance, in this case, users can use the Box Select tool and select a range of the histogram shown, dynamically remapping the colors used in the plot to cover the selected range.\n",
    "\n",
    "The other two plots should be identical in appearance, but with the numerical array output of `rasterize()` mapped into RGB colors by Datashader itself, in Python (\"server-side\"), which allows some special Datashader computations described below but prevents other Bokeh-based features like hover and colorbars from being used. Here we've instructed Datashader to use the same colormap used by bokeh, so that the plots look similar, but as you can see the `rasterize()` colormap is determined by a HoloViews plot option, while the `shade` and `datashade` colormap is determined by an argument to those operations. See ``hv.help(rasterize)``,  ``hv.help(shade)``, and ``hv.help(datashade)`` for options that can be selected, and the [Datashader web site](http://datashader.org) for all the details. HoloViews also provides lower-level `aggregate()` and `regrid()` operations that implement `rasterize()` and give more control over how the data is aggregated, but these are not needed for typical usage."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Setting options\n",
    "\n",
    "By their nature, the datashading operations accept one HoloViews Element type and return a different Element type. Regardless of what type they are given, `rasterize()` returns an `hv.Image`, while `shade()` and `datashade()` return an `hv.RGB`. It is important to keep this transformation in mind, because HoloViews options that you set on your original Element type are not normally transferred to your new Element:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "points2 = decimate(points, dynamic=False, max_samples=3000)\n",
    "points2.opts(color=\"green\", size=6, marker=\"s\")\n",
    "\n",
    "points2 + rasterize(points2).relabel(\"Rasterized\") + datashade(points2).relabel(\"Datashaded\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The datashaded plot represents each point as a single pixel, many of which are very difficult to see, and you can see that the color, size, and marker shape that you set on the Points element will not be applied to the rasterized or datashaded plot, because `size` and `marker` are not directly applicable to the numerical arrays of `hv.Image` and the pixel arrays of `hv.RGB`. \n",
    "\n",
    "If you want to use Datashader to recreate the options from the original plot, you can usually do so, but you will have to use the various Datashader-specific features explained in the sections below along with HoloViews options specifically for `hv.Image` or `hv.RGB`. For example:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "w=225\n",
    "\n",
    "points2 + \\\n",
    "spread(rasterize(points2, width=w, height=w), px=4, shape='square').opts(cmap=[\"green\"]).relabel(\"Rasterized\") + \\\n",
    "spread(datashade(points2, width=w, height=w, cmap=[\"green\"]), px=4, shape='square').relabel(\"Datashaded\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Note that by forcing the single-color colormap `[\"green\"]`, Datashader's support for avoiding overplotting has been lost. In most cases you will want to reveal the underlying distribution while avoiding overplotting, either by using a proper colormap (**Rasterized** below) or by using the alpha channel to convey the number of overlapping points (**Datashaded** below)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import bokeh.palettes as bp\n",
    "greens = bp.Greens[256][::-1][64:]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "points2 + \\\n",
    "spread(rasterize(points2, width=w, height=w), px=4, shape='square').opts(cmap=greens, cnorm='eq_hist').relabel(\"Rasterized\") +\\\n",
    "spread(datashade(points2, width=w, height=w, cmap=\"green\", cnorm='eq_hist'), px=4, shape='square').relabel(\"Datashaded\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Colormapping\n",
    "\n",
    "As you can see above, the choice of colormap and the various colormapping options can be very important for datashaded plots. One issue often seen in large, real-world datasets is that there is structure at many spatial and value scales, which requires special attention to colormapping options. This example dataset from the [Datashader documentation](https://datashader.org/getting_started/Pipeline.html) illustrates the issues, with data clustering at five different spatial scales:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "num=10000\n",
    "np.random.seed(1)\n",
    "\n",
    "dists = {cat: pd.DataFrame(dict([('x',np.random.normal(x,s,num)), \n",
    "                                 ('y',np.random.normal(y,s,num)), \n",
    "                                 ('val',val), \n",
    "                                 ('cat',cat)]))      \n",
    "         for x,  y,  s,  val, cat in \n",
    "         [(  2,  2, 0.03, 10, \"d1\"), \n",
    "          (  2, -2, 0.10, 20, \"d2\"), \n",
    "          ( -2, -2, 0.50, 30, \"d3\"), \n",
    "          ( -2,  2, 1.00, 40, \"d4\"), \n",
    "          (  0,  0, 3.00, 50, \"d5\")] }\n",
    "\n",
    "df = pd.concat(dists,ignore_index=True)\n",
    "df[\"cat\"]=df[\"cat\"].astype(\"category\")\n",
    "df"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Each of the five categories has 10000 points, but distributed over different spatial areas. Bokeh supports three colormap normalization options, which each behave differently:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "ropts = dict(tools=[\"hover\"], height=380, width=330, colorbar=True, colorbar_position=\"bottom\")\n",
    "\n",
    "hv.Layout([rasterize(hv.Points(df)).opts(**ropts).opts(cnorm=n).relabel(n)\n",
    "           for n in [\"linear\", \"log\", \"eq_hist\"]])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Here, the `linear` map is easy to interpret, but nearly all of the pixels are drawn in the lightest blue, because the highest-count pixel (around a count of 6000) is much larger in value than the typical pixels. The other two plots show the full structure (five concentrations of data points, including one in the background), with `log` using a standard logarithmic transformation of the count data before colormapping, and `eq_hist` using a histogram-equalization technique (see the [Datashader docs](https://datashader.org/getting_started/Pipeline.html)) to reveal structure without any assumptions about the incoming distribution (but with an irregularly spaced colormap that makes the numeric values difficult to reason about). In practice, it is generally a good idea to use `eq_hist` when exploring a large dataset initially, so that you will see any structure present, then switch to `log` or `linear` as appropriate to share the plots with a simpler-to-explain colormap. All three of these options are supported by the various backends (including Bokeh version 2.2.3 or later)  and by `shade()` and `datashade()` except that `eq_hist` is not yet available for the Plotly backend."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Since datashader only sends the data currently in view to the plotting backend, the default behavior is to rescale the colormap to the range of the visible data as the zoom level changes. This behavior may not be desirable when working with images; to instead use a fixed colormap range, the `clim` parameter can be passed to the `bokeh` backend via the `opts()` method. Note that this approach works with `rasterize()` where the colormapping is done by the `bokeh` backend. With `datashade()`, the colormapping is done with the `shade()` function which takes a `clims` parameter directly instead of passing additional parameters to the backend via `opts()`. For example (removing the semicolon in a live notebook to see the output):"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "pts1 = rasterize(hv.Points(df)).opts(**ropts).opts(tools=[], cnorm='log', axiswise=True)\n",
    "pts2 = rasterize(hv.Points(df)).opts(**ropts).opts(tools=[], cnorm='log', axiswise=True)\n",
    "\n",
    "pts1 + pts2.opts(clim=(0, 10000));"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<img src=\"http://assets.holoviews.org/gifs/guides/user_guide/Large_Data/rasterize_clim_example.gif\"></img>\n",
    "\n",
    "By default, pixels with an integer count of zero or a floating-point value of NaN are transparent, letting the plot background show through so that the data can be used in overlays. If you want zero to map to the lowest colormap color instead to make a dense, fully filled-in image, you can use `redim.nodata` to set the `Dimension.nodata` parameter to None:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "hv.Layout([rasterize(hv.Points(df), vdim_prefix='').redim.nodata(Count=n)\\\n",
    "           .opts(**ropts, cnorm=\"eq_hist\").relabel(\"nodata=\"+str(n))\n",
    "           for n in [0, None]])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Spreading and antialiasing\n",
    "\n",
    "By default, Datashader treats points and lines as infinitesimal in width, such that a given point or small bit of line segment appears in at most one pixel. This approach ensures that the overall distribution of the points will be mathematically well founded -- each pixel will scale in value directly by the number of points that fall into it, or by the lines that cross it. As a consequence, Datashader's \"marker size\" and \"line width\" are effectively one pixel by default.\n",
    "\n",
    "However, many monitors are sufficiently high resolution that a single-pixel point or line can be difficult to see---one pixel may not be visible at all on its own, and even if it is visible it is often difficult to see its color. To compensate for this, HoloViews provides access to Datashader's raster-based \"spreading\" (a generalization of image dilation and convolution), which makes isolated nonzero cells \"spread\" into adjacent ones for visibility.  There are two varieties of spreading supported:\n",
    "\n",
    "1. ``spread``: fixed spreading of a certain number of cells (pixels), which is useful if you want to be sure how much spreading is done regardless of the properties of the data.\n",
    "2. ``dynspread``: spreads up to a maximum size as long as it does not exceed a specified fraction of adjacency between cells (pixels) (controlled by a `threshold` parameter).\n",
    "\n",
    "Dynamic spreading is typically more useful for interactive plotting, because it adjusts depending on how close the datapoints are to each other on screen. As of Datashader 0.12, both types of spreading are supported for both `rasterize()` and `shade()`, but previous Datashader versions only support spreading on the RGB output of `shade()`.\n",
    "\n",
    "As long as you have Datashader 0.12 or later, you can compare the results when you zoom the two plots below; when you zoom in far enough you should be able to see that the in the two zoomed-in plots below, then zoom out to see that the plots are the same when points are clustered together to form a distribution. (If running a live notebook; remove the semicolon so that you see the live output rather than the saved GIF.)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "pts = rasterize(points).opts(cnorm='eq_hist')\n",
    "\n",
    "pts + dynspread(pts);"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<img src=\"http://assets.holoviews.org/gifs/guides/user_guide/Large_Data/dynspread.gif\"></img>\n",
    "\n",
    "Both plots show the same data, and look identical when zoomed out, but when zoomed in enough you should be able to see the individual data points on the right while the ones on the left are barely visible.  The dynspread parameters typically need some hand tuning, as the only purpose of such spreading is to make things visible on a particular monitor for a particular observer; the underlying mathematical operations in Datashader do not normally need parameters to be adjusted.\n",
    "\n",
    "Dynspread is not usable with connected plots like trajectories or curves, because the spreading amount is measured by the fraction of cells that have neighbors closer than the given spread distance, which is always 100% when datapoints are connected together. For connected plots you can instead use `spread` with a fixed value to expand patterns by `px` in every direction after they are drawn, or (for Datashader 0.14 or later) pass an explicit width like `line_width=1` to the rasterizer (at some cost in performance) to draw fully antialiased lines with the specified width:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "rasterize(paths).relabel(\"Rasterized\") + \\\n",
    "spread(rasterize(paths), px=1).relabel(\"Spread 1\") + \\\n",
    "rasterize(paths, line_width=2).relabel(\"Antialiased line_width 2\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Multidimensional plots\n",
    "\n",
    "The above plots show two dimensions of data plotted along *x* and *y*, but Datashader operations can be used with additional dimensions as well.  For instance, an extra dimension (here called `k`), can be treated as a category label and used to colorize the points or lines, aggregating the data points separately depending on which category value they have. Compared to a standard overlaid scatterplot that would suffer from overplotting, here the result will be merged mathematically by Datashader, completely avoiding any overplotting issues except any local issues that may arise from spreading when zoomed in:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "np.random.seed(3)\n",
    "kdims=['d1','d2']\n",
    "num_ks=8\n",
    "\n",
    "def rand_gauss2d(value=0, n=100000):\n",
    "    \"\"\"Return a randomly shaped 2D Gaussian distribution with an associated numeric value\"\"\"\n",
    "    g = 100*np.random.multivariate_normal(np.random.randn(2), random_cov(), (n,))\n",
    "    return np.hstack((g,value*np.ones((g.shape[0],1))))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "gaussians = {str(i): hv.Points(rand_gauss2d(i), kdims, \"i\") for i in range(num_ks)}\n",
    "\n",
    "c = dynspread(datashade(hv.NdOverlay(gaussians, kdims='k'), aggregator=ds.by('k', ds.count())))\n",
    "m = dynspread(datashade(hv.NdOverlay(gaussians, kdims='k'), aggregator=ds.by('k', ds.mean(\"i\"))))\n",
    "\n",
    "c.opts(width=400) + m.opts(width=400)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Above you can see that (as of Datashader 0.11) categorical aggregates can take any reduction function, either `count`ing the datapoints (left) or reporting some other statistic (e.g. the mean value of a column, right). This type of categorical mixing is currently only supported by `shade()` and `datashade()`, not `rasterize()` alone, because it depends on Datashader's custom color mixing code.\n",
    "\n",
    "Categorical aggregates are one way to allow separate lines or other shapes to be visually distinctive from one another while avoiding obscuring data due to overplotting:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "lines = {str(i): hv.Curve(time_series(N=10000, S0=200+np.random.rand())) for i in range(num_ks)}\n",
    "lineoverlay = hv.NdOverlay(lines, kdims='k')\n",
    "datashade(lineoverlay, pixel_ratio=2, line_width=4, aggregator=ds.by('k', ds.count())).opts(width=800)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "As you can see, overlapping colors yield color mixtures that indicate that the given pixels contain data from multiple curves, which helps users realize where they need to zoom in to see further detail.\n",
    "\n",
    "Note that Bokeh only ever sees an image come out of `datashade`, not any of the actual data. As a result, providing legends and keys has to be done separately, though we are hoping to make this process more seamless.  For now, you can show a legend by adding a suitable collection of \"fake\" labeled points (size zero and thus invisible):"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# definition copied here to ensure independent pan/zoom state for each dynamic plot\n",
    "gaussspread2 = dynspread(datashade(hv.NdOverlay(gaussians, kdims=['k']), aggregator=ds.by('k', ds.count())))\n",
    "\n",
    "from datashader.colors import Sets1to3 # default datashade() and shade() color cycle\n",
    "color_key = list(enumerate(Sets1to3[0:num_ks]))\n",
    "color_points = hv.NdOverlay({k: hv.Points([(0,0)], label=str(k)).opts(color=v, size=0) for k, v in color_key})\n",
    "\n",
    "(color_points * gaussspread2).opts(width=600)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Here the dummy points are at (0,0) for this dataset, but would need to be at another suitable value for data that is in a different range."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Working with time series\n",
    "\n",
    "HoloViews also makes it possible to datashade large timeseries using the ``datashade`` and ``rasterize`` operations. For smoother lines, datashader implements anti-aliasing if a `line_width` > 0 is set:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "dates = pd.date_range(start=\"2014-01-01\", end=\"2016-01-01\", freq='1D') # or '1min'\n",
    "curve = hv.Curve((dates, time_series(N=len(dates), sigma = 1)))\n",
    "rasterize(curve, width=800, line_width=3, pixel_ratio=2).opts(width=800, cmap=['lightblue','blue'])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Here we're also doubling the resolution in x and y using `pixel_ratio=2`, allowing for more precise rendering of the line shape; higher pixel ratios work well for lines and other shapes, though they can make individual points more difficult to see in points plots.\n",
    "\n",
    "HoloViews also supplies some operations that are useful in combination with Datashader timeseries.  For instance, you can compute a rolling mean of the results and then show a subset of outlier points, which will then support hover, selection, and other interactive Bokeh features:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from holoviews.operation.timeseries import rolling, rolling_outlier_std\n",
    "smoothed = rolling(curve, rolling_window=50)\n",
    "outliers = rolling_outlier_std(curve, rolling_window=50, sigma=2)\n",
    "\n",
    "ds_curve    = rasterize(curve, line_width=2.5, pixel_ratio=2).opts(cmap=[\"lightblue\",\"blue\"])\n",
    "curvespread = rasterize(smoothed, line_width=6, pixel_ratio=2).opts(cmap=[\"pink\",\"red\"], width=800) \n",
    "\n",
    "(ds_curve * curvespread * outliers).opts(\n",
    "    opts.Scatter(line_color=\"black\", fill_color=\"red\", size=10, tools=['hover', 'box_select'], width=800))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Another option when working with time series is to downsample the data before plotting it. This can be done with `downsample1D`. Algorithms supported are `lttb` (Largest Triangle Three Buckets) and `nth` element. The two algorithm is overlaid on top of the original curve in the example below. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from holoviews.operation.downsample import downsample1d\n",
    "\n",
    "lttb = downsample1d(curve)\n",
    "nth = downsample1d(curve, algorithm=\"nth\")\n",
    "\n",
    "lttb_com = (curve * lttb).opts(width=800, title=\"lttb comparison\")\n",
    "nth_com = (curve * nth).opts(width=800, title=\"nth comparison\")\n",
    "\n",
    "(lttb_com + nth_com).cols(1)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The result of all these operations can be laid out, overlaid, selected, and sampled just like any other HoloViews element, letting you work naturally with even very large datasets.\n",
    "\n",
    "Note that the above plot will look blocky in a static export (such as on anaconda.org), because the exported version is generated without taking the size of the actual plot (using default height and width for Datashader) into account, whereas the live notebook automatically regenerates the plot to match the visible area on the page. "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Element types supported for Datashading\n",
    "\n",
    "Fundamentally, what Datashader does is to rasterize data, i.e., render a representation of it into a regularly gridded rectangular portion of a two-dimensional plane.  Datashader natively supports six basic types of rasterization:\n",
    "\n",
    "- **points**: zero-dimensional objects aggregated by position alone, each point covering zero area in the plane and thus falling into exactly one grid cell of the resulting array (if the point is within the bounds being aggregated).\n",
    "- **line**: polyline/multiline objects (connected series of line segments), with each segment having a fixed length but either zero width (not antialiased) or a specified width, and crossing each grid cell at most once.\n",
    "- **area**: a region to fill either between the supplied y-values and the origin or between two supplied lines.\n",
    "- **trimesh**: irregularly spaced triangular grid, with each triangle covering a portion of the 2D plane and thus potentially crossing multiple grid cells (thus requiring interpolation/upsampling). Depending on the zoom level, a single pixel can also include multiple triangles, which then becomes similar to the `points` case (requiring aggregation/downsampling of all triangles covered by the pixel).\n",
    "- **raster**: an axis-aligned regularly gridded two-dimensional subregion of the plane, with each grid cell in the source data covering more than one grid cell in the output grid (requiring interpolation/upsampling), or with each grid cell in the output grid including contributions from more than one grid cell in the input grid (requiring aggregation/downsampling).\n",
    "- **quadmesh**: a recti-linear or curvi-linear mesh (like a raster, but allowing nonuniform spacing and coordinate mapping) where each quad can cover one or more cells in the output (requiring upsampling, currently only as nearest neighbor), or with each output grid cell including contributions from more than one input grid cell (requiring aggregation/downsampling).\n",
    "- **polygons**:  arbitrary filled shapes in 2D space (bounded by a piecewise linear set of segments), optionally punctuated by similarly bounded internal holes.\n",
    "\n",
    "Datashader focuses on implementing those four cases very efficiently, and HoloViews in turn can use them to render a very large range of specific types of data: \n",
    "\n",
    "### Supported Elements\n",
    "\n",
    "- **points**: [`hv.Nodes`](../reference/elements/bokeh/Graph.ipynb), [`hv.Points`](../reference/elements/bokeh/Points.ipynb), [`hv.Scatter`](../reference/elements/bokeh/Scatter.ipynb)\n",
    "- **line**: [`hv.Contours`](../reference/elements/bokeh/Contours.ipynb), [`hv.Curve`](../reference/elements/bokeh/Curve.ipynb), [`hv.Path`](../reference/elements/bokeh/Path.ipynb), [`hv.Graph`](../reference/elements/bokeh/Graph.ipynb), [`hv.EdgePaths`](../reference/elements/bokeh/Graph.ipynb), [`hv.Spikes`](../reference/elements/bokeh/Spikes.ipynb), [`hv.Segments`](../reference/elements/bokeh/Segments.ipynb)\n",
    "- **area**: [`hv.Area`](../reference/elements/bokeh/Area.ipynb), [`hv.Rectangles`](../reference/elements/bokeh/Rectangles.ipynb), [`hv.Spread`](../reference/elements/bokeh/Spread.ipynb)\n",
    "- **raster**: [`hv.Image`](../reference/elements/bokeh/Image.ipynb), [`hv.HSV`](../reference/elements/bokeh/HSV.ipynb), [`hv.RGB`](../reference/elements/bokeh/RGB.ipynb)\n",
    "- **trimesh**: [`hv.TriMesh`](../reference/elements/bokeh/TriMesh.ipynb)\n",
    "- **quadmesh**: [`hv.QuadMesh`](../reference/elements/bokeh/QuadMesh.ipynb)\n",
    "- **polygons**: [`hv.Polygons`](../reference/elements/bokeh/Polygons.ipynb)\n",
    "\n",
    "Other HoloViews elements *could* be supported, but do not currently have a useful datashaded representation:\n",
    "\n",
    "### Elements not yet supported\n",
    "\n",
    "- **line**: [`hv.Spline`](../reference/elements/bokeh/Spline.ipynb), [`hv.VectorField`](../reference/elements/bokeh/VectorField.ipynb)\n",
    "- **raster**: [`hv.HeatMap`](../reference/elements/bokeh/HeatMap.ipynb), [`hv.Raster`](../reference/elements/bokeh/Raster.ipynb)\n",
    "\n",
    "There are also other Elements that are not expected to be useful with datashader because they are isolated annotations, are already summaries or aggregations of other data, have graphical representations that are only meaningful at a certain size, or are text based:\n",
    "\n",
    "### Not useful to support\n",
    "\n",
    "- datashadable annotations: [`hv.Arrow`](../reference/elements/bokeh/Arrow.ipynb), [`hv.Bounds`](../reference/elements/bokeh/Bounds.ipynb), [`hv.Box`](../reference/elements/bokeh/Box.ipynb), [`hv.Ellipse`](../reference/elements/bokeh/Ellipse.ipynb) (actually do work with datashade currently, but not officially supported because they are not vectorized and thus unlikely to have enough items to be worth datashading)\n",
    "- other annotations: [`hv.Labels`](../reference/elements/bokeh/Labels.ipynb), [`hv.HLine`](../reference/elements/bokeh/HLine.ipynb), [`hv.VLine`](../reference/elements/bokeh/VLine.ipynb), [`hv.Text`](../reference/elements/bokeh/Text.ipynb)\n",
    "- kdes: [`hv.Distribution`](../reference/elements/bokeh/Distribution.ipynb), [`hv.Bivariate`](../reference/elements/bokeh/Bivariate.ipynb) (already aggregated)\n",
    "- categorical/symbolic: [`hv.BoxWhisker`](../reference/elements/bokeh/BoxWhisker.ipynb), [`hv.Bars`](../reference/elements/bokeh/Bars.ipynb), [`hv.ErrorBars`](../reference/elements/bokeh/ErrorBars.ipynb)\n",
    "- tables: [`hv.Table`](../reference/elements/bokeh/Table.ipynb), [`hv.ItemTable`](../reference/elements/bokeh/ItemTable.ipynb)\n",
    "\n",
    "Let's make some examples of each supported Element type. First, some dummy data:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from bokeh.sampledata.unemployment import data as unemployment\n",
    "from bokeh.sampledata.us_counties import data as counties\n",
    "\n",
    "np.random.seed(12)\n",
    "N=50\n",
    "pts = [(10*i/N, np.sin(10*i/N)) for i in range(N)]\n",
    "\n",
    "x = y = np.linspace(0, 5, int(np.sqrt(N)))\n",
    "xs,ys = np.meshgrid(x,y)\n",
    "z = np.sin(xs)*np.cos(ys)\n",
    "\n",
    "r = 0.5*np.sin(0.1*xs**2+0.05*ys**2)+0.5\n",
    "g = 0.5*np.sin(0.02*xs**2+0.2*ys**2)+0.5\n",
    "b = 0.5*np.sin(0.02*xs**2+0.02*ys**2)+0.5\n",
    "\n",
    "n=20\n",
    "coords = np.linspace(-1.5,1.5,n)\n",
    "X,Y = np.meshgrid(coords, coords);\n",
    "Qx = np.cos(Y) - np.cos(X)\n",
    "Qy = np.sin(Y) + np.sin(X)\n",
    "Z = np.sqrt(X**2 + Y**2)\n",
    "\n",
    "rect_colors = {True: 'red', False: 'green'}\n",
    "s = np.random.randn(100).cumsum()\n",
    "e = s + np.random.randn(100)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Next, some options:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "hv.output(backend='matplotlib')\n",
    "\n",
    "opts.defaults(opts.Layout(vspace=0.1, hspace=0.1, sublabel_format='', fig_size=48))\n",
    "eopts = dict(aspect=1, axiswise=True, xaxis='bare', yaxis='bare', xticks=False, yticks=False)\n",
    "opts2 = dict(filled=True, edge_color='z')\n",
    "rect_opts = opts.Rectangles(lw=0, color=hv.dim('sign').categorize(rect_colors))\n",
    "ds_point_opts = dict(aggregator='any')\n",
    "ds_line_opts  = dict(aggregator='any', line_width=1)\n",
    "ResampleOperation2D.width=115\n",
    "ResampleOperation2D.height=115\n",
    "\n",
    "ds_opts = {\n",
    "    hv.Path:       ds_line_opts,\n",
    "    hv.Graph:      ds_line_opts,\n",
    "    hv.Contours:   ds_line_opts,\n",
    "    hv.EdgePaths:  ds_line_opts,\n",
    "    hv.Curve:      ds_line_opts,\n",
    "    hv.Scatter:    ds_point_opts,\n",
    "    hv.Points:     ds_point_opts,\n",
    "    hv.Segments:   ds_point_opts,\n",
    "    hv.Rectangles: dict(aggregator=ds.count_cat('sign'), color_key=rect_colors)\n",
    "}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now, some Elements that support datashading, in categories depending on whether they work best with `spread(rasterize())`, with plain `rasterize()`, or require `datashade()`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "tri = hv.TriMesh.from_vertices(hv.Points(np.random.randn(N,3), vdims='z')).opts(**opts2)\n",
    "\n",
    "rasterizable  = [hv.Curve(pts)]\n",
    "rasterizable += [hv.operation.contours(hv.Image((x,y,z)), levels=10)]\n",
    "rasterizable += [hv.Area(np.random.randn(10000).cumsum())]\n",
    "rasterizable += [hv.Spread((np.arange(10000), np.random.randn(10000).cumsum(), np.random.randn(10000)*10))]\n",
    "rasterizable += [hv.Spikes(np.random.randn(1000))]\n",
    "rasterizable += [hv.Graph(((np.zeros(N//2), np.arange(N//2)),))]\n",
    "rasterizable += [hv.QuadMesh((Qx,Qy,Z))]\n",
    "rasterizable += [hv.Image((x,y,z))]\n",
    "rasterizable += [hv.RGB(np.dstack([r,g,b])), hv.HSV(np.dstack([g,b,r]))]\n",
    "rasterizable += [tri, tri.edgepaths]\n",
    "rasterizable += [hv.Path(counties[(1, 1)], ['lons', 'lats'])]\n",
    "\n",
    "polys = hv.Polygons([dict(county, unemployment=unemployment[k]) \n",
    "                     for k, county in counties.items()\n",
    "                     if county['state'] == 'tx'], \n",
    "                    ['lons', 'lats'], ['unemployment']).opts(color='unemployment')\n",
    "try:\n",
    "    import spatialpandas # Needed for datashader polygon support\n",
    "    rasterizable += [polys]\n",
    "except: pass\n",
    "\n",
    "spreadable  = [e(pts) for e in [hv.Scatter]]\n",
    "spreadable += [hv.Points(counties[(1, 1)], ['lons', 'lats'])]\n",
    "spreadable += [hv.Segments((np.arange(100), s, np.arange(100), e))]\n",
    "\n",
    "shadeable  = [hv.Rectangles((np.arange(100)-0.4, s, np.arange(100)+0.4, e, s>e), vdims='sign').opts(rect_opts)]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We can now view these with Datashader via `spread(rasterize())`, `rasterize()`, or `datashade()`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def nop(x,**k):      return x\n",
    "def spread2(e, **k): return spread(rasterize(e, **k), px=2).opts(cnorm='eq_hist', padding=0.1) \n",
    "def plot(e, operation=nop):\n",
    "    return operation(e.relabel(e.__class__.name), **ds_opts.get(e.__class__, {})).opts(**eopts)\n",
    "\n",
    "hv.Layout(\n",
    "    [plot(e, rasterize) for e in rasterizable] + \\\n",
    "    [plot(e, spread2)   for e in spreadable] + \\\n",
    "    [plot(e, datashade) for e in shadeable]).cols(6)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "For comparison, you can see the corresponding non-datashaded plots (as long as you leave N lower than 10000 unless you have a long time to wait!):"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "hv.Layout([plot(e) for e in rasterizable + spreadable + shadeable]).cols(6)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The previous two sets of examples use Matplotlib, but if they were switched to Bokeh and you had a live server, they would support dynamic re-rendering on zoom and pan so that you could explore the full range of data available (e.g. even very large raster images, networks, paths, point clouds, or meshes)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "hv.output(backend='bokeh') # restore bokeh backend in case cells will run out of order"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Container types supported for datashading\n",
    "\n",
    "In the above examples `datashade()` or `rasterize` was called directly on each Element, but these operations can also be called on Containers, in which case each Element in the Container will be datashaded separately (for all Container types other than a Layout):"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "curves = {'+':hv.Curve(pts), '-':hv.Curve([(x, -1.0*y) for x, y in pts])}\n",
    "rasterize(hv.HoloMap(curves,'sign'), line_width=3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "rasterize(hv.NdLayout(curves,'sign'), line_width=3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "containers = [hv.Overlay(list(curves.values())), hv.NdOverlay(curves), hv.GridSpace(hv.NdOverlay(curves))]\n",
    "hv.Layout([rasterize(e.relabel(e.__class__.name), line_width=3) for e in containers]).cols(3)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Optimizing performance\n",
    "\n",
    "Datashader and HoloViews have different design principles that are worth keeping in mind when using them in combination, if you want to ensure good overall performance. By design, Datashader supports only a small number of operations and datatypes, focusing only on what can be implemented very efficiently.  HoloViews instead focuses on supporting the typical workflows of Python users, recognizing that the most computationally efficient choice is only going to be faster overall if it also minimizes the time users have to spend getting things working. \n",
    "\n",
    "HoloViews thus helps you get something working quickly, but once it is working and you realize that you need to do this often or that it comes up against the limits of your computing hardware, you can consider whether you can get much better performance by considering the following issues and suggestions.\n",
    "\n",
    "### Use a Datashader-supported data structure\n",
    "\n",
    "HoloViews helpfully tries to convert whatever data you have provided into what Datashader supports, which is good for optimizing your time to an initial solution, but will not always be the fastest approach computationally.  If you ensure that you store your data in a format that Datashader understands already, HoloViews can simply pass it down to Datashader without copying or transforming it:\n",
    "\n",
    "1. For point, line, and trimesh data, Datashader supports Dask and Pandas dataframes, and so those two data sources will be fastest. Of those two, Dask Dataframes will usually be somewhat faster and also able to make use of distributed computational resources and out-of-core processing.\n",
    "2. For rasters and quadmeshes, Datashader supports xarray objects natively, and so if your data is provided as an xarray already, plotting will be faster.\n",
    "3. For polygons Datashader supports [spatialpandas](https://github.com/holoviz/spatialpandas) DataFrames.\n",
    "\n",
    "See the [Datashader docs](http://datashader.org) for examples of dealing with even quite large datasets (in the billions of points) on commodity hardware, including many HoloViews-based examples.\n",
    "\n",
    "### Cache initial processing with `precompute=True`\n",
    "\n",
    "In the typical case of having datasets much larger than the plot resolution, HoloViews Datashader-based operations that work on the full dataset (`rasterize`, `aggregate`,`regrid`) are computationally expensive; the others are not (`shade`, `spread`, `dynspread`, etc.) \n",
    "\n",
    "The expensive operations are all of type `ResamplingOperation`, which has a parameter `precompute` (see `hv.help(hv.operation.datashader.rasterize)`, etc.)  Precompute can be used to get faster performance in interactive usage by caching the last set of data used in plotting (*after* any transformations needed) and reusing it when it is requested again. This is particularly useful when your data is not in one of the supported data formats already and needs to be converted. `precompute` is False by default, because it requires using memory to store the cached data, but if you have enough memory, you can enable it so that repeated interactions (such as zooming and panning) will be much faster than the first one.  In practice, most Datashader-plots don't need to do extensive precomputing, but enabling it for TriMesh and Polygon plots can greatly speed up interactive usage.\n",
    "\n",
    "### Use GPU support\n",
    "\n",
    "Many elements now also support aggregation directly on a GPU-based datastructure such as a [cuDF DataFrame](https://github.com/rapidsai/cudf) or an Xarray DataArray backed by a [cupy](https://github.com/cupy/cupy) array. These data structures can be passed directly to the appropriate HoloViews elements just as you would use a Pandas or other Xarray object. For instance, a cuDF can be used on elements like `hv.Points` and `hv.Curve`, while a cupy-backed DataArray raster or quadmesh can be passed to `hv.QuadMesh` elements. When used with Datashader, the GPU implementation can result in 10-100x speedups, as well as avoiding having to transfer the data out of the GPU for plotting (sending only the final rendered plot out of the GPU's memory). To see which HoloViews elements are supported, see the [datashader performance guide](https://datashader.org/user_guide/Performance.html). As of the Datashader 0.11 release, all point, line, area, and quadmesh aggregations are supported when using a GPU backed datastructure, including raster objects like `hv.Image` if first converted to `hv.Quadmesh`.\n",
    "\n",
    "### Project data only once\n",
    "\n",
    "If you are working with geographic data using [GeoViews](http://geoviews.org) that needs to be projected before display and/or before datashading, GeoViews will have to do this every time you update a plot, which can drown out the performance improvement you get by using Datashader.  GeoViews allows you to project the entire dataset at once using `gv.operation.project`, and once you do this you should be able to use Datashader at full speed.\n",
    "\n",
    "If you follow these suggestions, the combination of HoloViews and Datashader will allow you to work uniformly with data covering a huge range of sizes. Per session or per plot, you can trade off the ability to export user-manipulable plots against file size and browser compatibility, and allowing you to render even the largest dataset faithfully. HoloViews makes the full power of Datashader available in just a few lines of code, giving you a natural way to work with your data regardless of its size."
   ]
  }
 ],
 "metadata": {
  "language_info": {
   "name": "python",
   "pygments_lexer": "ipython3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
