# How to Plot a Polars DataFrame in Python

> Plot a Polars DataFrame with df.plot.line(), df.plot.bar(), and df.plot.point(), which return Altair charts, or pass it to Plotly, Matplotlib, Seaborn, or hvPlot.

Source: https://www.pythoncharts.com/python/polars-plotting/ | Published: 2026-11-27 | Author: Alex Scott | Category: Python | Tags: polars, altair, hvplot, plotting, line chart, bar chart

To plot a Polars DataFrame, call a method on `df.plot`, such as
`df.plot.line(x="week", y="kwh", color="station")`. Polars doesn't draw anything
itself: `df.plot` hands the data to [Altair](https://altair-viz.github.io/) and
returns an Altair chart that you can customize further.

This post uses Polars 2.2.0 and Altair 6.2.2 (`pip install polars altair`).
`df.plot` needs Altair 5.4 or later. It doesn't need pandas or pyarrow.

## Quick Example

```python
import numpy as np
import polars as pl

# Weekly energy delivered at three EV charging stations (made-up data).
rng = np.random.default_rng(12)
weeks = pl.date_range(pl.date(2026, 1, 5), pl.date(2026, 6, 29), "1w", eager=True)
n = len(weeks)

energy = pl.concat(
    pl.DataFrame({
        "week": weeks,
        "station": station,
        "kwh": (base + growth * np.arange(n) + rng.normal(0, 90, n)).round(),
    })
    for station, base, growth in [
        ("Airport", 2600, 55), ("Downtown", 2100, 22), ("Mall", 1200, 38),
    ]
)

chart = energy.plot.line(x="week", y="kwh", color="station").properties(
    width=500, height=300, title="Weekly Energy Delivered by Station"
)
chart
```

![Altair line chart from a Polars DataFrame showing weekly energy rising at the Airport, Downtown, and Mall charging stations, with Airport highest](https://www.pythoncharts.com/python/polars-plotting/images/polars-plot-quick-example.png)

Jupyter, VS Code notebooks, and Colab display the chart when it's the last line
of a cell. From a script, call `chart.show()` to open it in a browser, or
[save it to a file](#save-a-polars-chart-as-png-or-html).

## What can df.plot draw?

`df.plot.line(...)` is shorthand for
`alt.Chart(df).mark_line(tooltip=True).encode(...).interactive()`, so every chart
has tooltips and supports zooming and panning.

| Method | Chart |
|---|---|
| `df.plot.line()` | Line chart |
| `df.plot.bar()` | Bar chart |
| `df.plot.point()` or `df.plot.scatter()` | Scatter plot |
| `df.plot.area()`, `.boxplot()`, `.rect()`, ... | Any other Altair `mark_*` method |
| `df["col"].plot.hist()` | Histogram |
| `df["col"].plot.kde()` | Density plot |
| `df["col"].plot.line()` | Values against their row number |

There's no `df.plot.pie()`, because Altair calls that mark `arc`. Use
`df.plot.arc(theta="value", color="category")` with your own column names.

## How do I make a bar chart from a Polars DataFrame?

Aggregate with `group_by()`, then plot the result. `alt.X(..., sort="-y")` orders
the bars from largest to smallest. Without it, Altair sorts the categories
alphabetically, whatever order the rows are in.

```python
import altair as alt

totals = energy.group_by("station").agg(pl.col("kwh").sum() / 1000)

chart = totals.plot.bar(
    x=alt.X("station", sort="-y", title=None, axis=alt.Axis(labelAngle=0)),
    y=alt.Y("kwh", title="Energy (MWh)"),
).properties(width=500, height=300, title="Total Energy, January to June")
chart
```

![Bar chart of total energy by charging station sorted from largest to smallest: Airport, Downtown, then Mall](https://www.pythoncharts.com/python/polars-plotting/images/polars-bar-chart.png)

Plain column names work for `x`, `y`, and `color`. Switch to `alt.X`, `alt.Y`,
or `alt.Color` when you need a title, sort order, scale, or axis settings.
[Altair axis titles and formatting](https://www.pythoncharts.com/altair/altair-axis-titles-formatting/)
covers the options.

## Stacked and grouped bar charts

A `color` column stacks the bars. Add `xOffset` with the same column to place
them side by side.

```python
monthly = (
    energy.group_by(pl.col("week").dt.month().alias("month"), "station")
    .agg(pl.col("kwh").sum() / 1000)
    .sort("month", "station")
    .with_columns(pl.date(2026, "month", 1).dt.strftime("%b").alias("month_name"))
)

x = alt.X("month_name", sort=None, title=None, axis=alt.Axis(labelAngle=0))
y = alt.Y("kwh", title="Energy (MWh)")

stacked = monthly.plot.bar(x=x, y=y, color="station").properties(
    width=200, height=280, title="Stacked"
)
grouped = monthly.plot.bar(x=x, y=y, color="station", xOffset="station").properties(
    width=300, height=280, title="Grouped"
)
chart = stacked | grouped
chart
```

![Stacked and grouped bar charts of monthly energy by charging station from January to June](https://www.pythoncharts.com/python/polars-plotting/images/polars-stacked-grouped-bars.png)

`sort=None` keeps the months in the DataFrame's row order. The `|` operator puts
two charts side by side; see
[layering and concatenating Altair charts](https://www.pythoncharts.com/altair/altair-layer-concat-charts/).
Combining two `df.plot` charts can print a warning that Altair "deduplicated" a
selection parameter, which refers to their shared zoom and pan setting. The
charts above still render.

## Scatter plot with color and size

`df.plot.point()` accepts `color` and `size`. A list of column names in `tooltip`
adds them to the hover box.

```python
sessions_n = 220
charger = rng.choice(["Level 2", "DC fast"], sessions_n, p=[0.6, 0.4])
fast = charger == "DC fast"
minutes = np.where(fast, rng.gamma(9, 3.5, sessions_n).clip(10, 70),
                   rng.gamma(6, 24, sessions_n).clip(30, 360))
power = np.where(fast, rng.normal(68, 12, sessions_n), rng.normal(6.4, 0.8, sessions_n))
kwh = minutes / 60 * power

sessions = pl.DataFrame({
    "charger": charger,
    "minutes": minutes.round(),
    "kwh": kwh.round(1),
    "cost": (kwh * np.where(fast, 0.52, 0.28)).round(2),
})

chart = sessions.plot.point(
    x=alt.X("minutes", title="Session length (minutes)"),
    y=alt.Y("kwh", title="Energy (kWh)"),
    color=alt.Color("charger", title="Charger"),
    size=alt.Size("cost", title="Cost ($)"),
    tooltip=["charger", "minutes", "kwh", "cost"],
).properties(width=500, height=320, title="Charging Sessions")
chart
```

![Scatter plot of session length against energy, with DC fast sessions short and steep and Level 2 sessions long and low](https://www.pythoncharts.com/python/polars-plotting/images/polars-scatter-plot.png)

The y-axis starts at zero by default. For data far from zero, use
`alt.Y("kwh", scale=alt.Scale(zero=False))`.

## Histogram and density plot from a Series

Select one column and use `.plot.hist()` or `.plot.kde()`. To change the number
of bins, replace the x encoding with `.encode()`. Passing `x=` to `hist()` itself
raises a `TypeError`, because the method already sets it.

```python
length = sessions.filter(pl.col("charger") == "Level 2")["minutes"]

hist = length.plot.hist().encode(
    x=alt.X("minutes", bin=alt.Bin(maxbins=25), title="Minutes")
).properties(width=240, height=260, title="Histogram")

density = length.plot.kde().properties(width=240, height=260, title="Density")

chart = hist | density
chart
```

![Histogram and density plot of Level 2 charging session lengths](https://www.pythoncharts.com/python/polars-plotting/images/polars-histogram-kde.png)

## Plot wide data with unpivot()

Altair expects long data: one column for the values and one that names the
series. If each series has its own column, reshape with `unpivot()` first (called
`melt()` before Polars 1.0).

```python
wide = energy.pivot(on="station", index="week", values="kwh")

long = wide.unpivot(index="week", variable_name="station", value_name="kwh")

chart = long.plot.area(
    x=alt.X("week", title=None),
    y=alt.Y("kwh", title="Energy (kWh)"),
    color="station",
).properties(width=500, height=300, title="Combined Weekly Energy")
chart
```

![Stacked area chart of weekly energy for three charging stations after unpivoting a wide Polars DataFrame](https://www.pythoncharts.com/python/polars-plotting/images/polars-wide-data-area.png)

## Add layers and labels

The result of `df.plot` is a regular `alt.Chart`, so Altair's operators and
methods work on it. Here `+` layers a reference line and `mark_text()` writes the
values at the top of the bars.

```python
bars = totals.plot.bar(
    x=alt.X("station", sort="-y", title=None, axis=alt.Axis(labelAngle=0)),
    y=alt.Y("kwh", title="Energy (MWh)"),
)
labels = bars.mark_text(dy=14, color="white", fontWeight="bold").encode(
    text=alt.Text("kwh", format=".1f")
)
average = alt.Chart(totals).mark_rule(color="crimson", strokeDash=[6, 4]).encode(
    y="mean(kwh)"
)

chart = (bars + labels + average).properties(
    width=500, height=300, title="Station Totals and Average"
)
chart
```

![Bar chart of station totals with value labels and a dashed red line marking the average](https://www.pythoncharts.com/python/polars-plotting/images/polars-layered-labels.png)

The average line uses `alt.Chart(totals)` on purpose. Every `df.plot` chart
comes with its own zoom and pan setting, and layering this bar chart, its labels,
and a `totals.plot.rule()` fails to render with
`Duplicate signal name` in Altair 6.2.2. Start extra layers from `alt.Chart()`.

## Save a Polars chart as PNG or HTML

Use `chart.save()`. The file extension picks the format. HTML works with Altair
alone and stays interactive; PNG, SVG, and PDF also need
`pip install vl-convert-python`.

```python
chart.save("station-totals.html")
chart.save("station-totals.png", scale_factor=2)
```

`scale_factor=2` doubles the pixel dimensions for a sharper image. More options
are in [how to save Altair charts](https://www.pythoncharts.com/altair/save-altair-charts/).

## How do I fix MaxRowsError?

Altair stores the data inside the chart, and by default raises `MaxRowsError`
for more than 5,000 rows. The best fix is usually to aggregate in Polars first,
which keeps the chart small and fast.

```python
readings = pl.DataFrame({
    "time": pl.datetime_range(
        pl.datetime(2026, 6, 1), pl.datetime(2026, 6, 14, 23, 59), "1m", eager=True
    )
}).with_columns(
    kw=(60 + 45 * (pl.col("time").dt.hour() - 6).mul(np.pi / 12).sin()
        + pl.Series(rng.normal(0, 9, 14 * 1440))).clip(0)
)
print(readings.height)  # 20160

hourly = readings.group_by_dynamic("time", every="1h").agg(pl.col("kw").mean())

chart = hourly.plot.line(
    x=alt.X("time", title=None, axis=alt.Axis(format="%b %d")), y=alt.Y("kw", title="Average power (kW)")
).properties(width=500, height=260, title="Hourly Average of 20,160 Readings")
chart
```

![Line chart of hourly average charging power over two weeks, showing a daily cycle](https://www.pythoncharts.com/python/polars-plotting/images/polars-aggregated-time-series.png)

If you need every row, call `alt.data_transformers.disable_max_rows()`. The data
is then embedded in the notebook or HTML file, so large frames make large, slow
pages. For millions of points,
[Datashader](https://www.pythoncharts.com/python/datashader-millions-points/)
is a better tool.

## Use Polars with Plotly, Matplotlib, or Seaborn

You don't have to use Altair.

```python
import matplotlib.pyplot as plt
import plotly.express as px
import seaborn as sns

# Plotly Express takes a Polars DataFrame directly.
fig = px.line(energy, x="week", y="kwh", color="station")

# Matplotlib takes Polars Series.
plt.figure(figsize=(7, 4))
airport = energy.filter(pl.col("station") == "Airport")
plt.plot(airport["week"], airport["kwh"])
plt.show()

# Seaborn: pass a dictionary of columns.
plt.figure(figsize=(7, 4))
sns.lineplot(data=energy.to_dict(), x="week", y="kwh", hue="station")
plt.show()
```

Plotly Express also needs NumPy installed. Seaborn 0.13.2 rejects a Polars 2.2
DataFrame with `TypeError: Data source must be a DataFrame or Mapping`.
`data=energy.to_dict()` works without extra packages, and
`data=energy.to_pandas()` works if pandas and pyarrow are installed.

## Use hvPlot instead of Altair

hvPlot was the engine behind `df.plot` before Polars 1.6. It's still available
under `df.hvplot` after you import `hvplot.polars`, and it draws with Bokeh by
default. Install it with `pip install hvplot pyarrow`.

```python
import hvplot.polars  # noqa: F401  (adds df.hvplot)

energy.hvplot.line(x="week", y="kwh", by="station", title="Weekly Energy")
```

Note that hvPlot groups series with `by=`, where Altair uses `color=`. Older
tutorials that call `df.plot.line(..., by=...)` were written for the hvPlot
backend and need `df.hvplot` today.

See the [hvPlot guide](https://www.pythoncharts.com/python/hvplot-pandas-interactive-plots/) for widgets, overlays and large datasets.

## Which should I use?

| Goal | Use |
|---|---|
| Quick interactive chart while exploring | `df.plot` |
| Layered or linked interactive charts | `df.plot`, then Altair |
| Pie charts, 3D charts, dashboards with Dash | Plotly Express |
| Publication figures with full control | Matplotlib |
| Statistical plots such as pair plots | Seaborn |
| Code written for the old hvPlot `df.plot` | `df.hvplot` |

[Python interactive charting libraries compared](https://www.pythoncharts.com/python/python-interactive-charting-libraries-compared/)
looks at the interactive options side by side.

## Practical tips

- Aggregate and filter in Polars before plotting. It's faster than asking Altair to do it in the browser.
- Rename columns that contain `.`, `[`, or `:` with `df.rename()` before plotting. Altair reads them as syntax: a column named `a.b` or `a[0]` draws an empty chart, and `a:b` raises a `ValueError`.
- A `LazyFrame` has no `.plot`. Call `.collect()` first.
- For tables instead of charts, [Great Tables](https://www.pythoncharts.com/python/great-tables-python/) also accepts Polars DataFrames.

## Similar Topics

- [A Brief Introduction to Altair](https://www.pythoncharts.com/altair/intro-to-altair/)
- [How to Plot GroupBy and Pivot Table Results in Pandas](https://www.pythoncharts.com/pandas/pandas-plot-groupby/)
- [Layer and Concatenate Charts in Altair](https://www.pythoncharts.com/altair/altair-layer-concat-charts/)
