Datashader

Plot tens of millions of points by aggregating them into an image-sized grid on the server – the browser never receives more pixels than it can show, and zooming in re-aggregates automatically.

Datashader plots millions of rows by aggregating them into an image on the server, so the browser receives the same amount whatever the row count. You use it through HoloViews or hvPlot (rasterize() or datashade()), and render the result with @render_holoviews.

hero

1,000,000 synthetic ride-hail pickups clustered around NYC landmarks, aggregated to one image on the server. Try the app.

Installation

pip install 'shinywidgets[holoviews]' datashader hvplot

shinywidgets[holoviews] brings in holoviews, panel, and jupyter_bokeh (which serves its JavaScript locally, so apps work offline). datashader and hvplot are not part of that extra – add them yourself. Every example below uses hvPlot’s rasterize=/datashade= kwargs, the fastest way in; the lower-level holoviews.operation.datashader functions (rasterize(), datashade(), dynspread()) are equivalent and used directly in a couple of examples.

Quick start

One million synthetic ride-hail pickups, clustered around real NYC landmarks (Times Square, Wall Street, JFK, LaGuardia, Central Park) with a Gaussian spread around each:

# A million synthetic ride-hail pickups, clustered around real NYC landmarks
# (Times Square, Wall Street, JFK, LaGuardia, Central Park) with a Gaussian
# spread around each -- rasterize=True turns them into a single image-sized
# grid on the server, so the browser never sees more than one plot's worth
# of pixels no matter how many rows went in.
import numpy as np
import pandas as pd
import hvplot.pandas  # noqa: F401 -- registers the .hvplot accessor
from shiny.express import ui

from shinywidgets import render_holoviews

N = 1_000_000
LANDMARKS = {
    "Times Square": (40.758, -73.985, 0.010),
    "Wall Street": (40.706, -74.009, 0.006),
    "JFK Airport": (40.641, -73.778, 0.020),
    "LaGuardia": (40.777, -73.872, 0.015),
    "Central Park": (40.782, -73.965, 0.015),
    "Williamsburg": (40.714, -73.957, 0.012),
    "Astoria": (40.772, -73.930, 0.012),
}

rng = np.random.default_rng(0)
names = list(LANDMARKS)
weights = rng.dirichlet(np.ones(len(names)) * 3)
counts = rng.multinomial(N, weights)
lat, lon = [], []
for name, c in zip(names, counts):
    lat0, lon0, spread = LANDMARKS[name]
    lat.append(rng.normal(lat0, spread, c))
    lon.append(rng.normal(lon0, spread, c))
pickups = pd.DataFrame({"lat": np.concatenate(lat), "lon": np.concatenate(lon)})

ui.page_opts(title=f"{N:,} synthetic ride-hail pickups", fillable=True)


@render_holoviews
def plot():
    return pickups.hvplot.points(
        "lon", "lat", rasterize=True, cnorm="eq_hist", cmap="fire",
        responsive=True, colorbar=True, title="Pickup density",
    )

rasterize=True is the whole integration: hvPlot wraps the points in a DynamicMap, aggregates them into a grid sized to the output’s pixels, and colors that grid with cmap. cnorm="eq_hist" (histogram-equalized color scaling) is almost always what you want for real data – it keeps sparse outskirts visible next to dense cores, which a linear scale would wash out to a single color. The million rows never leave the server; only an image does.

Overview

A look at what you can build. Click any of them to open the app, with its code, in Shinylive.

Aggregating and styling

Each of the following is a plain hvPlot/Datashader option – nothing Shiny-specific yet.

rasterize vs datashade

Same 500,000 points, two operations:

# rasterize=True sends a scalar field with a live colorbar and hover values;
# datashade=True bakes the colors into an RGBA image server-side instead --
# no colorbar or hover, but a smaller payload.
import numpy as np
import pandas as pd
import hvplot.pandas  # noqa: F401
from shiny.express import ui

from shinywidgets import render_holoviews

N = 500_000
LANDMARKS = {
    "Times Square": (40.758, -73.985, 0.010),
    "Wall Street": (40.706, -74.009, 0.006),
    "JFK Airport": (40.641, -73.778, 0.020),
}
rng = np.random.default_rng(0)
names = list(LANDMARKS)
weights = rng.dirichlet(np.ones(len(names)) * 3)
counts = rng.multinomial(N, weights)
lat, lon = [], []
for name, c in zip(names, counts):
    lat0, lon0, spread = LANDMARKS[name]
    lat.append(rng.normal(lat0, spread, c))
    lon.append(rng.normal(lon0, spread, c))
pickups = pd.DataFrame({"lat": np.concatenate(lat), "lon": np.concatenate(lon)})

ui.page_opts(title="rasterize vs datashade", fillable=True)

with ui.layout_columns():
    with ui.card(full_screen=True):
        ui.card_header("rasterize=True -- colorbar + hover values")

        @render_holoviews
        def raster():
            return pickups.hvplot.points(
                "lon", "lat", rasterize=True, cnorm="eq_hist", cmap="fire",
                responsive=True, colorbar=True,
            )

    with ui.card(full_screen=True):
        ui.card_header("datashade=True -- no colorbar/hover, smaller payload")

        @render_holoviews
        def shade():
            return pickups.hvplot.points(
                "lon", "lat", datashade=True, cnorm="eq_hist", cmap="fire",
                responsive=True,
            )

rasterize vs datashade

rasterize=True sends a scalar field (counts, or an aggregate) and lets HoloViews apply the colormap client-side – you get a live colorbar and hover tooltips with the underlying value. datashade=True bakes the colors into an RGBA image on the server instead – no colorbar, no hover, but a smaller payload. Default to rasterize when you want hover/colorbar; reach for datashade when payload size matters more, or when you need count_cat with a color_key – categorical coloring is datashade’s native mode.

Choosing an aggregator

The same 500,000 rows, three ways:

# Three aggregators over the same 500,000 rows: count (density), mean of a
# numeric column (fare), and count_cat (density per category, with a color
# key and legend instead of a colorbar).
import datashader as ds
import holoviews as hv
import numpy as np
import pandas as pd
import hvplot.pandas  # noqa: F401
from shiny.express import ui

from shinywidgets import render_holoviews

hv.extension("bokeh")

N = 500_000
LANDMARKS = {
    "Times Square": (40.758, -73.985, 0.010),
    "Wall Street": (40.706, -74.009, 0.006),
    "JFK Airport": (40.641, -73.778, 0.020),
    "LaGuardia": (40.777, -73.872, 0.015),
}
rng = np.random.default_rng(0)
names = list(LANDMARKS)
weights = rng.dirichlet(np.ones(len(names)) * 3)
counts = rng.multinomial(N, weights)
lat, lon, place = [], [], []
for name, c in zip(names, counts):
    lat0, lon0, spread = LANDMARKS[name]
    lat.append(rng.normal(lat0, spread, c))
    lon.append(rng.normal(lon0, spread, c))
    place.extend([name] * c)
pickups = pd.DataFrame({"lat": np.concatenate(lat), "lon": np.concatenate(lon), "place": pd.Categorical(place)})
# JFK fares run higher, on top of the base gamma-distributed fare
pickups["fare"] = rng.gamma(2.0, 6.0, len(pickups)) + (pickups.place == "JFK Airport") * 40

ui.page_opts(title="Aggregators", fillable=True)

with ui.layout_columns():
    with ui.card(full_screen=True):
        ui.card_header("count (default)")

        @render_holoviews
        def by_count():
            return pickups.hvplot.points(
                "lon", "lat", rasterize=True, aggregator="count",
                cnorm="eq_hist", cmap="fire", responsive=True, colorbar=True,
            )

    with ui.card(full_screen=True):
        ui.card_header("mean(fare)")

        @render_holoviews
        def by_mean():
            return pickups.hvplot.points(
                "lon", "lat", rasterize=True, aggregator=ds.mean("fare"),
                cmap="viridis", responsive=True, colorbar=True,
                clabel="mean fare ($)",
            )

    with ui.card(full_screen=True):
        ui.card_header("count_cat(place)")

        @render_holoviews
        def by_cat():
            return pickups.hvplot.points(
                "lon", "lat", datashade=True, aggregator=ds.count_cat("place"),
                color_key="Category10", responsive=True, legend="top_right",
            )

aggregators

aggregator="count" (the default) shows density. ds.mean("fare") colors each pixel by the average of a numeric column instead – in this synthetic data, JFK pickups run a higher fare, and the mean(fare) panel picks that out in a way the density panel can’t. ds.count_cat("place") aggregates per category and renders each pixel as a blend of per-category colors from color_key, with a legend – this needs datashade, not rasterize, since the category blending happens as part of the RGBA conversion. Any datashader.reductions aggregator works the same way: ds.sum(), ds.max(), ds.std(), and more are documented in Datashader’s aggregation guide.

Making isolated points visible

A rasterized image only shows what lands in each pixel – a single isolated point is one pixel, easy to miss next to a dense cluster that fills hundreds. dynspread() grows isolated pixels until they’re a few pixels wide, without growing pixels in dense regions (it inspects local density and spreads adaptively). The example below zooms into a sparse corner so the effect is visible without an interactive zoom:

# A sparse, uniformly-scattered layer (stranded dropoffs far from the main
# cluster) rasterizes to isolated single pixels that are easy to miss at a
# normal screen density. dynspread grows isolated pixels until they're a few
# pixels wide, without doing anything to dense regions where pixels already
# overlap. xlim/ylim below zoom into a sparse corner so the effect is visible
# without needing to zoom interactively.
import numpy as np
import pandas as pd
import hvplot.pandas  # noqa: F401
from shiny.express import ui

from shinywidgets import render_holoviews

rng = np.random.default_rng(1)
dense = pd.DataFrame({
    "lon": rng.normal(-73.985, 0.01, 400_000),
    "lat": rng.normal(40.758, 0.01, 400_000),
})
sparse = pd.DataFrame({
    "lon": rng.uniform(-74.05, -73.75, 4_000),
    "lat": rng.uniform(40.60, 40.85, 4_000),
})
pts = pd.concat([dense, sparse], ignore_index=True)

XLIM, YLIM = (-73.82, -73.76), (40.74, 40.80)

ui.page_opts(title="dynspread", fillable=True)

with ui.layout_columns():
    with ui.card(full_screen=True):
        ui.card_header("rasterize only -- isolated points are 1px, easy to miss")

        @render_holoviews
        def no_spread():
            return pts.hvplot.points(
                "lon", "lat", rasterize=True, cnorm="eq_hist", cmap="fire",
                responsive=True, xlim=XLIM, ylim=YLIM,
            )

    with ui.card(full_screen=True):
        ui.card_header("+ dynspread(max_px=6) -- isolated points become visible dots")

        @render_holoviews
        def with_spread():
            return pts.hvplot.points(
                "lon", "lat", rasterize=True, dynspread=True, max_px=6,
                cnorm="eq_hist", cmap="fire", responsive=True,
                xlim=XLIM, ylim=YLIM,
            )

dynspread

Without dynspread, this sparse layer (stranded points scattered far from the main cluster) is almost entirely invisible – each point is a single, barely-there pixel. dynspread=True, max_px=6 (or the standalone holoviews.operation.datashader.dynspread() function) turns every isolated point into a visible dot. Use it whenever your data has both dense clusters and meaningful outliers you don’t want to lose.

Lines at scale

Datashader rasterizes lines as well as points – a long or busy time series rasterizes to a clean, antialiased curve instead of an unreadable tangle of overlapping strokes. The example below overlays 5 synthetic sensor traces, 200,000 samples each (1,000,000 points total), datashaded with one color per category:

# Datashader rasterizes lines too, not just points: 5 synthetic sensor
# traces (200,000 samples each, 1,000,000 points total) overlaid and
# datashaded with one color per category -- a continuous line, not discrete
# markers, so individual samples never show up as clutter.
import datashader as ds
import holoviews as hv
import numpy as np
import pandas as pd
from holoviews.operation.datashader import datashade
from shiny.express import ui

from shinywidgets import render_holoviews

hv.extension("bokeh")

N_PER_SENSOR = 200_000
K = 5
rng = np.random.default_rng(0)
frames = []
for i in range(K):
    v = np.cumsum(rng.normal(0, 1, N_PER_SENSOR)) * 0.03 + i * 3
    frames.append(pd.DataFrame({"t": np.arange(N_PER_SENSOR), "v": v, "sensor": f"sensor {i}"}))
readings = pd.concat(frames, ignore_index=True)
readings["sensor"] = readings["sensor"].astype("category")

ui.page_opts(title=f"{len(readings):,} samples across {K} sensors", fillable=True)


@render_holoviews
def traces():
    overlay = hv.NdOverlay(
        {s: hv.Curve(g, "t", "v") for s, g in readings.groupby("sensor", observed=True)},
        kdims="sensor",
    )
    return datashade(
        overlay,
        aggregator=ds.count_cat("sensor"),
        color_key=hv.Cycle("Category10").values[:K],
    ).opts(responsive=True, title=f"{K} sensors, {N_PER_SENSOR:,} samples each")

lines at scale

The same count_cat + color_key recipe from the aggregators section works for an NdOverlay of curves, not just points: each category gets a distinct, antialiased color, and the 1,000,000 total samples never individually hit the DOM. hvPlot’s own .line(datashade=True) does the same thing for a single long curve.

Reacting to interaction

Datashader plots have no accessors of their own – interactivity follows the same stream-based model the HoloViews guide covers for any DynamicMap. What’s specific here: rasterize() and datashade() attach their own stream for you, which is what makes re-aggregation on zoom automatic with no code beyond rasterize=True/datashade=True.

Re-aggregation on zoom

This is Datashader’s headline feature in an interactive app: zoom in, and the server re-aggregates just the visible region, so detail invisible at the full extent sharpens into view instead of staying a blur.

The same stream driving that re-aggregation can also be read into Shiny, to compute exact stats on the full dataframe for whatever’s currently in view – not just what datashader rasterized:

# Re-aggregation on zoom is automatic -- hvPlot's rasterize=True attaches its
# own internal hv.streams.RangeXY to the DynamicMap, so scrolling to zoom
# re-runs datashader for just the visible region with no code to write.
# This example also reads that same internal RangeXY stream into Shiny, to
# show a "points in view" stat computed on the full data (not just the
# rasterized pixels). The subscriber stores the range tuple itself (an
# idempotent `.set()`) rather than a counter, so repeated reports of the
# same range don't re-run readers for nothing.
import holoviews as hv
import numpy as np
import pandas as pd
import hvplot.pandas  # noqa: F401
from holoviews.streams import RangeXY
from shiny import reactive
from shiny.express import render, ui

from shinywidgets import render_holoviews

hv.extension("bokeh")

N = 1_000_000
LANDMARKS = {
    "Times Square": (40.758, -73.985, 0.010),
    "Wall Street": (40.706, -74.009, 0.006),
    "JFK Airport": (40.641, -73.778, 0.020),
    "LaGuardia": (40.777, -73.872, 0.015),
    "Central Park": (40.782, -73.965, 0.015),
}
rng = np.random.default_rng(0)
names = list(LANDMARKS)
weights = rng.dirichlet(np.ones(len(names)) * 3)
counts = rng.multinomial(N, weights)
lat, lon = [], []
for name, c in zip(names, counts):
    lat0, lon0, spread = LANDMARKS[name]
    lat.append(rng.normal(lat0, spread, c))
    lon.append(rng.normal(lon0, spread, c))
pickups = pd.DataFrame({"lat": np.concatenate(lat), "lon": np.concatenate(lon)})

ui.page_opts(title="Zoom stats", fillable=True)

view_range = reactive.value(None)


@render_holoviews
def plot():
    img = pickups.hvplot.points(
        "lon", "lat", rasterize=True, cnorm="eq_hist", cmap="fire", responsive=True,
    )
    rng_stream = next(s for s in img.streams if isinstance(s, RangeXY))
    rng_stream.add_subscriber(lambda x_range, y_range: view_range.set((x_range, y_range)))
    return img


@render.text
def n_in_view():
    r = view_range()
    if r is None or r[0][0] is None:
        return f"{len(pickups):,} in view (full extent)"
    (x0, x1), (y0, y1) = r
    sel = pickups[pickups.lon.between(x0, x1) & pickups.lat.between(y0, y1)]
    return f"{len(sel):,} in view"

Grab the stream rasterize()/datashade() already created (next(s for s in img.streams if isinstance(s, RangeXY))) and add a second subscriber to it, rather than constructing a redundant hv.streams.RangeXY(source=img) of your own – one stream reporting the viewport is simpler than two. Store the range tuple itself with .set() (idempotent – reactive.Value skips invalidation when the new value equals the old one), not a counter or anything that changes on every call, so repeated reports of the same range don’t re-run readers for nothing. This combination re-renders exactly once per gesture, even at 1,000,000 points.

Box-select for exact stats

Zoom gives you “whatever’s currently in view”; a box-select gives you a smaller, deliberate region, via hv.streams.BoundsXY – the same recipe the HoloViews guide uses, which works the same way on a rasterized image:

# A box-select brush can be smaller and more deliberate than "whatever's
# currently zoomed in" -- hv.streams.BoundsXY fires once per drag, and the
# bounds become a pandas mask over the FULL 500,000-row dataframe (not just
# the pixels datashader drew), so stats like mean fare are exact.
import holoviews as hv
import numpy as np
import pandas as pd
import hvplot.pandas  # noqa: F401
from holoviews.streams import BoundsXY
from shiny import reactive
from shiny.express import render, ui

from shinywidgets import render_holoviews

hv.extension("bokeh")

N = 500_000
LANDMARKS = {
    "Times Square": (40.758, -73.985, 0.010),
    "Wall Street": (40.706, -74.009, 0.006),
    "JFK Airport": (40.641, -73.778, 0.020),
}
rng = np.random.default_rng(0)
names = list(LANDMARKS)
weights = rng.dirichlet(np.ones(len(names)) * 3)
counts = rng.multinomial(N, weights)
lat, lon = [], []
for name, c in zip(names, counts):
    lat0, lon0, spread = LANDMARKS[name]
    lat.append(rng.normal(lat0, spread, c))
    lon.append(rng.normal(lon0, spread, c))
pickups = pd.DataFrame({"lat": np.concatenate(lat), "lon": np.concatenate(lon)})
pickups["fare"] = rng.gamma(2.0, 6.0, len(pickups))

ui.page_opts(title="Box-select stats on the full data", fillable=True)

selected_bounds = reactive.value(None)

with ui.layout_columns():
    with ui.card(full_screen=True):
        ui.card_header("Drag a box (box-select tool is active by default)")

        @render_holoviews
        def plot():
            img = pickups.hvplot.points(
                "lon", "lat", rasterize=True, cnorm="eq_hist", cmap="fire",
                responsive=True, tools=["box_select"],
            ).opts(active_tools=["box_select"])
            # the subscriber's parameter must be named "bounds" -- BoundsXY
            # calls it with that keyword
            BoundsXY(source=img).add_subscriber(lambda bounds: selected_bounds.set(bounds))
            return img

    with ui.card():
        ui.card_header("Stats on the full 500,000-row data")

        @render.ui
        def stats():
            b = selected_bounds()
            if b is None:
                return ui.p("Drag a box to select a region.", class_="text-muted")
            x0, y0, x1, y1 = b
            sel = pickups[pickups.lon.between(x0, x1) & pickups.lat.between(y0, y1)]
            return ui.TagList(
                ui.h5(f"{len(sel):,} of {len(pickups):,} rows"),
                ui.p(f"mean fare: ${sel.fare.mean():.2f}" if len(sel) else "mean fare: -"),
            )

The subscriber’s parameter must be named bounds – a differently-named parameter fails silently, so check the server log, not the browser, if a box-select subscriber seems to do nothing. Once wired up, bounds unpacks to (x0, y0, x1, y1) in data coordinates, and a pandas boolean mask over the original dataframe gives exact row counts and aggregates (here, len(sel) and sel.fare.mean()) – numbers datashader’s own pixel grid can’t give you, since it only ever computed one aggregate per pixel.

Updating in place

Re-rendering on every input change is simple but resets the user’s zoom – annoying for a plot whose whole point is “zoom in for detail.” The fix is the same one the HoloViews guide uses for any DynamicMap: give the operation a param.Parameter reference instead of a literal value, and update that parameter from a @reactive.effect. rasterize()’s aggregator= argument accepts a param.Parameter directly; a category filter needs one more step, since excluding rows changes the input element, not just how it’s colored – hv.streams.Params rebuilds a DynamicMap’s input when a param changes, and rasterize() wraps that DynamicMap, inheriting its own RangeXY/PlotSize streams across the rebuild:

# Shiny inputs (a landmark filter, an aggregator choice) drive the SAME
# rasterized plot in place instead of returning a new object from the render
# function: a per-session param.Parameterized holds the current choices,
# hv.streams.Params rebuilds the input points when the filter changes, and
# rasterize's aggregator accepts a param reference directly. Both update
# without resetting the user's zoom/pan (try zooming in first).
import datashader as ds
import holoviews as hv
import numpy as np
import pandas as pd
import param
from holoviews.operation.datashader import rasterize
from holoviews.streams import Params
from shiny import reactive
from shiny.express import input, ui

from shinywidgets import render_holoviews

hv.extension("bokeh")

N = 500_000
LANDMARKS = {
    "Times Square": (40.758, -73.985, 0.010),
    "Wall Street": (40.706, -74.009, 0.006),
    "JFK Airport": (40.641, -73.778, 0.020),
}
rng = np.random.default_rng(0)
names = list(LANDMARKS)
weights = rng.dirichlet(np.ones(len(names)) * 3)
counts = rng.multinomial(N, weights)
lat, lon, place = [], [], []
for name, c in zip(names, counts):
    lat0, lon0, spread = LANDMARKS[name]
    lat.append(rng.normal(lat0, spread, c))
    lon.append(rng.normal(lon0, spread, c))
    place.extend([name] * c)
pickups = pd.DataFrame({"lat": np.concatenate(lat), "lon": np.concatenate(lon), "place": pd.Categorical(place)})
pickups["fare"] = rng.gamma(2.0, 6.0, len(pickups))

ui.page_opts(title="Inputs update the plot in place", fillable=True)
ui.input_selectize("places", "Landmarks", choices=names, selected=names, multiple=True)
ui.input_radio_buttons("agg", "Aggregator", choices=["count", "mean fare"], selected="count")


class Style(param.Parameterized):
    categories = param.List(default=names)
    agg = param.Parameter(default=ds.count())


style = Style()  # one per session (Express re-runs this module per session)


def make_points(categories):
    sub = pickups[pickups.place.isin(categories)]
    return hv.Points(sub, ["lon", "lat"], ["fare"])


@reactive.effect
def _update_style():
    style.categories = list(input.places())
    style.agg = ds.count() if input.agg() == "count" else ds.mean("fare")


@render_holoviews
def plot():
    points_dmap = hv.DynamicMap(make_points, streams=[Params(style, ["categories"])])
    return rasterize(points_dmap, aggregator=style.param.agg).opts(
        responsive=True, cmap="fire", cnorm="eq_hist", colorbar=True,
    )

Zoomed into the JFK cluster, then switching the aggregator and removing JFK from the filter – the zoom survives both:

The last screenshot shows an empty view: zoomed into JFK, then JFK itself gets excluded by the filter. The plot correctly shows nothing in that region (rather than, say, resetting the view) – exactly the behavior you want from an in-place update. gallery/showcase_nyc_pickups_explorer.py combines this in-place filter/aggregator switch with the box-select stats panel above into one dashboard.

Large data

Datashader’s own API, rasterize() (used through render_holoviews, not a dedicated render_datashader), is the point of this guide: every example above bins millions of rows into a fixed-size image server-side, so message size and render cost are set by screen resolution, not row count. A plain scatter’s payload grows with the row count and eventually stops being practical at all; rasterize()’s payload stays flat regardless of how much data went in, because it’s always one image-sized frame, and re-aggregating on zoom stays fast enough to feel instant even at tens of millions of points. This is the “summarize on the server” approach from Large data & performance.

Points Plain scatter payload rasterize() payload
100,000 a few MB a few MB
1,000,000 tens of MB a few MB
10,000,000 too large to finish rendering a few MB

At real scale, push summaries instead of raw points when linking a brush to another view – see Linking widgets: brushing large data, which builds this exact raster + linked-histogram shape end to end.

Layout and sizing

Covered in full in the HoloViews guide: pass responsive=True (every example in this guide does) so the plot – and the aggregation region – fills its container, and give the output a fixed height plus fillable=True if you want a specific size rather than fill-the-card. The rasterized image resizes (and re-aggregates at the new pixel dimensions) the same way a plain Bokeh plot does.

Gotchas

  • Build the plot inside the render function, not at module level: a module-level plot is shared by every session, so one visitor’s zoom repaints everyone’s plot. Loading the data once at module level is fine.
  • A large aggregation delays every other session the same Shiny process serves until it finishes.

Learn more