hvPlot: Interactive Plots From pandas in One Line

Replace df.plot with df.hvplot for interactive charts: lines, bars, histograms, small multiples, overlays, widgets and large datasets.

To make an interactive plot from a pandas DataFrame, import hvplot.pandas and call df.hvplot.line() (or .bar(), .scatter(), .hist()) instead of df.plot. hvPlot builds the chart with HoloViews and draws it with Bokeh, so you get pan, zoom and hover tooltips. This post uses hvPlot 0.13 and HoloViews 1.23; install with pip install hvplot.

Quick Example

Weekly electricity generation from three sources for a made-up grid over two years.

import hvplot.pandas  # noqa: F401  (adds .hvplot to DataFrames)
import numpy as np
import pandas as pd

rng = np.random.default_rng(14)
weeks = pd.date_range("2024-01-07", periods=104, freq="W", name="week")
season = np.cos((weeks.dayofyear.to_numpy() - 172) / 365 * 2 * np.pi)  # +1 in late June
power = pd.DataFrame({
    "solar": 210 + 150 * season + np.arange(104) * 0.7 + rng.normal(0, 18, 104),
    "wind": 330 - 90 * season + rng.normal(0, 45, 104),
    "gas": 420 - 60 * season - np.arange(104) * 1.1 + rng.normal(0, 28, 104),
}, index=weeks).round(1)

plot = power.hvplot.line(
    title="Weekly generation by source", ylabel="GWh", xlabel="",
    color=["#f08c00", "#1971c2", "#868e96"], line_width=2,
    responsive=True, height=400, legend="top", group_label="Source",
)
plot

hvPlot line chart of two years of weekly solar, wind and gas generation; solar peaks in summer, wind in winter and gas trends down

Solar peaks each summer while wind peaks in winter, and gas trends down. In a notebook, the last line displays the chart. responsive=True makes it fill the width, and height sets the height in pixels.

Which Plot Methods Does hvPlot Have?

pandas hvPlot Draws
df.plot.line() df.hvplot.line() Lines, one per numeric column
df.plot.area() df.hvplot.area() Stacked areas
df.plot.bar() df.hvplot.bar() Bars
df.plot.scatter() df.hvplot.scatter() Points
df.plot.hist() df.hvplot.hist() Histograms
df.plot.box() df.hvplot.box() Box plots
df.plot.kde() df.hvplot.kde() Density curves (needs SciPy)
df.hvplot.heatmap() Heatmaps

Bar Charts

With a categorical index, each column becomes a series, and stacked=True stacks them. Convert numbers or dates to text first so each one gets its own labeled bar.

quarterly = power.resample("QS").sum()
quarterly.index = quarterly.index.to_period("Q").astype(str)  # text labels
quarterly.index.name = "quarter"

plot = quarterly.hvplot.bar(
    stacked=True, title="Generation per quarter", ylabel="GWh",
    color=["#f08c00", "#1971c2", "#868e96"], responsive=True, height=360,
    legend="right",
).opts(yformatter="%.0f", xrotation=45)
plot

Stacked bar chart of generation in each quarter of 2024 and 2025 split into solar, wind and gas

.opts() passes styling options on to HoloViews, such as yformatter for the tick format.

Group by a Column With by

For long-format data, by= draws one series per group, like hue in Seaborn. A scatter chart can also take its color from a numeric column with c=.

homes = pd.DataFrame({"heating": rng.choice(["Gas", "Heat pump"], 300)})
homes["outdoor"] = rng.uniform(-8, 16, 300).round(1)
slope = homes["heating"].map({"Gas": 3.1, "Heat pump": 1.2})
homes["kwh"] = (18 + slope * (17 - homes["outdoor"]) + rng.normal(0, 6, 300)).round(1)
homes = homes.sort_values("heating")  # colors follow the order groups appear

plot = homes.hvplot.scatter(
    x="outdoor", y="kwh", by="heating", alpha=0.7, size=40,
    color=["#c92a2a", "#0b7285"], xlabel="Outdoor temperature (°C)",
    ylabel="Heating energy per day (kWh)", responsive=True, height=380,
)
plot

Scatter of daily heating energy against outdoor temperature; gas homes rise more steeply in cold weather than heat pump homes

Gas-heated homes use more energy than heat pump homes, and the gap widens as it gets colder. The color list is matched to groups in the order they appear in the data, so sorting first puts red on Gas. In hvplot.scatter(), size is the marker area.

Small Multiples With subplots

subplots=True gives each group its own panel, and .cols() sets how many sit in a row.

plot = homes.hvplot.hist(
    "kwh", by="heating", subplots=True, bins=22, bin_range=(0, 110),
    color="#0b7285", width=290, height=280, xlabel="kWh per day",
).cols(2)
plot

Two histograms of daily heating energy, one for gas homes and one for heat pump homes

Overlay With * and Lay Out With +

hvPlot returns HoloViews objects, which combine with two operators. * draws one plot on top of another, and + puts plots side by side.

smooth = power["solar"].rolling(8, center=True).mean()

size = dict(responsive=True, height=340)
weekly = power["solar"].hvplot.scatter(color="#adb5bd", label="Weekly", **size)
trend = smooth.hvplot.line(color="#e8590c", line_width=3, label="8-week mean", **size)

plot = (weekly * trend).opts(title="Solar generation", ylabel="GWh", xlabel="",
                             legend_position="top_left")
plot

Grey weekly solar generation points with an orange 8-week rolling mean

For a side-by-side layout, write weekly + trend.

Add a Widget With groupby

groupby= turns a column into a dropdown or slider that picks which rows are drawn.

power_long = power.reset_index().melt("week", var_name="source", value_name="gwh")

plot = power_long.hvplot.line(x="week", y="gwh", groupby="source", width=650,
                              height=300, line_width=2,
                              widget_location="top_left")
plot

hvPlot line chart of one energy source with a dropdown for choosing the source

In a notebook the widget updates the chart. Saving to HTML stores the data for every choice in the file, so use it for a handful of options, not thousands.

Save an hvPlot Chart to HTML

import hvplot

hvplot.save(power.hvplot.line(), "generation.html")

Outside a notebook, a plot object displays nothing by itself. Use hvplot.show(plot) to open it in a browser, or save it. To tweak a plot with Bokeh directly, hvplot.render(plot) returns the Bokeh figure.

Plot a Million Points

rasterize=True aggregates the points into pixels with Datashader before sending them to the browser.

n = 1_000_000
cloud = pd.DataFrame({"x": rng.standard_normal(n)})
cloud["y"] = 0.6 * cloud["x"] + 0.8 * rng.standard_normal(n)

plot = cloud.hvplot.scatter("x", "y", rasterize=True, cmap="viridis",
                            cnorm="eq_hist", responsive=True, height=400,
                            title="One million points")
plot

Rasterized density plot of one million correlated points, brightest at the center

This needs Datashader installed. In a live notebook, zooming recomputes the image at full detail. In a saved file there is no Python running, so zooming only enlarges the pixels. See plotting millions of points with Datashader for more control.

Use hvPlot as the pandas Backend

Existing df.plot code can produce interactive charts after one setting. It requires HoloViews, which is installed with hvPlot.

pd.options.plotting.backend = "holoviews"
plot = power.plot.area(responsive=True, height=300)
pd.options.plotting.backend = "matplotlib"

When Should I Use hvPlot?

Choose When
hvPlot You already write df.plot and want interaction, widgets or large-data support
Bokeh You want to build the chart shape by shape
Plotly Express You want a wider set of chart types, including maps and 3D
df.plot with Matplotlib You need a static figure for a paper or report

hvPlot also works on Polars DataFrames with import hvplot.polars; see plotting a Polars DataFrame.

Similar Topics