Connect any database. Ask in plain English.

Try free
← Blog

Altair Python: 6 Chart Examples With Code, Saving to PNG and the 5,000-Row Limit (2026)

Vega-Altair 6.3.0 explained by building six charts on 4,734 invented orders: a bar, a time series, a heatmap, a bar-and-line layer, small multiples and an interactive brush with tooltips, each with its code and picture. Plus saving to HTML and PNG with vl-convert, the MaxRowsError you get past 5,000 rows and five ways round it, measured, and how Altair compares with matplotlib and Plotly.

Fastero Dev TeamFastero Dev Team2026-11-20

Vega-Altair is a Python charting library where you say which column goes on which axis and Altair works out the rest. We installed version 6.3.0 on 20 November 2026 and built six charts with it on a file of invented orders. Below is each chart's code and picture, how to save charts, and the 5,000-row limit you hit as soon as the data grows.

The short answer: Altair (pip install altair, version 6.3.0, Python 3.11 or later, checked 20 November 2026) turns a pandas DataFrame into a Vega-Lite chart. You pick a mark (mark_bar, mark_line, mark_rect), map columns to encodings (x, y, color, tooltip) with a type (:Q number, :N category, :O ordered, :T date), and Altair writes a JSON spec that a browser draws. chart.save("chart.html") keeps it interactive; chart.save("chart.png") needs the vl-convert-python package. Altair puts the data inside the chart and refuses more than 5,000 rows by default with a MaxRowsError: aggregate in pandas first, or turn on the VegaFusion data transformer.

Fastero

Connect your database. Ask questions. Get dashboards.

Postgres, BigQuery, Snowflake, and 10+ sources — live-connected, AI-powered, no dashboard builder learning curve.

Try free →

Install Altair

The docs give pip install "altair[all]" for every optional dependency and pip install "altair[save]" for saving to HTML, PNG, SVG and PDF. We installed the parts by hand in a fresh virtual environment:

pip install altair vl-convert-python pandas
python -c "import altair as alt, vl_convert as vlc; print(alt.__version__, vlc.__version__, alt.SCHEMA_URL)"
6.3.0 1.9.0 https://vega.github.io/schema/vega-lite/v6.4.1.json

So Altair 6.3.0 (released 15 September 2026) writes Vega-Lite 6.4.1 specs. Altair 6.0 moved to Vega-Lite 6, and 6.3.0 dropped Python 3.10. Everything below ran on Python 3.14.3 with pandas 3.1.1; we added vegafusion and pyarrow for the row-limit section.

How an Altair chart is built: marks, encodings and data types

Every chart is alt.Chart(data).mark_*().encode(...). The encoding names a column and its type. The docs list five types:

Type Shorthand The docs' description In our data
quantitative :Q "a continuous real-valued quantity" revenue
nominal :N "a discrete unordered category" region, category
ordinal :O "a discrete ordered quantity" months as heatmap columns
temporal :T "a time or date value" order_date
geojson :G "a geographic shape" none

From a DataFrame, Altair guesses: numbers are quantitative, dates temporal and text nominal, "but be aware that these defaults are by no means always the correct choice!" The shorthand also takes aggregates and time units, so "sum(revenue):Q" and "yearmonth(order_date):T" do the grouping inside the chart.

Altair chart examples

All six use sample-sales.csv: 4,734 invented orders from November 2024 to October 2026 with order_date, region, channel, category, product, quantity and revenue. A short theme set our fonts and colours; it's left out of the snippets.

import altair as alt
import pandas as pd
 
df = pd.read_csv("sample-sales.csv", parse_dates=["order_date"])

1. Bar chart

bar = alt.Chart(df).mark_bar(cornerRadiusEnd=4).encode(
    x=alt.X("sum(revenue):Q", title="Revenue ($)"),
    y=alt.Y("category:N", sort="-x", title=None),
    tooltip=["category:N", alt.Tooltip("sum(revenue):Q", format="$,.0f")],
).properties(title="Revenue by category", height=180)
bar.save("01-bar.png", scale_factor=2)

Horizontal Altair bar chart of revenue by category: Hardware about $704K, Software $374K, Supplies $198K, Services $197K

A bar chart in Altair, sorted by its own value with sort="-x". Invented data.

sort="-x" sorts the bars by their length, largest first. Putting the categories on y makes it horizontal.

2. Time series

line = alt.Chart(df).mark_line(point=True).encode(
    x=alt.X("yearmonth(order_date):T", title=None, axis=alt.Axis(format="%b %y")),
    y=alt.Y("sum(revenue):Q", title="Revenue ($)"),
    color=alt.Color("channel:N", title="Channel"),
    tooltip=[alt.Tooltip("yearmonth(order_date):T", title="Month"), "channel:N",
             alt.Tooltip("sum(revenue):Q", format="$,.0f", title="Revenue")],
).properties(title="Monthly revenue by channel")

Altair line chart of monthly revenue by channel from November 2024 to October 2026, Online highest at up to about $42.6K a month, then Sales team and Partner

One line per channel from a single color encoding. Invented data.

yearmonth(...) groups the orders by month, and color="channel:N" splits the line into one per channel with a legend.

3. Heatmap

heat = alt.Chart(df).mark_rect().encode(
    x=alt.X("yearmonth(order_date):O", title=None, axis=alt.Axis(format="%b %y", labelAngle=-45)),
    y=alt.Y("category:N", title=None),
    color=alt.Color("count():Q", title="Orders", scale=alt.Scale(range=["#cde2fb", "#0d366b"])),
    tooltip=[alt.Tooltip("yearmonth(order_date):T", title="Month"), "category:N",
             alt.Tooltip("count():Q", title="Orders")],
).properties(title="Orders by month and category", height=170)

Altair heatmap of orders by month and category, from 8 orders (Services, April 2025) to 109 (Hardware, July 2026), in light to dark blue

A heatmap: the month is ordinal (:O), so each one gets a cell. Invented data.

The month is :O here, not :T, so each month gets an equal cell. The busiest cell is Hardware in July 2026 with 109 orders; the quietest, Services in April 2025, with 8.

4. Layered bar and line

Monthly revenue as bars, its three-month average as a line, both on one axis. The transforms run in the chart:

monthly = alt.Chart(df).transform_timeunit(
    month="yearmonth(order_date)"
).transform_aggregate(
    revenue="sum(revenue)", groupby=["month"]
).transform_window(
    avg_3m="mean(revenue)", frame=[-2, 0], sort=[{"field": "month"}]
).encode(x=alt.X("month:O", title=None, timeUnit="yearmonth",
                 axis=alt.Axis(format="%b %y", labelAngle=-45)))
combo = (
    monthly.mark_bar(color="#9ec5f4", cornerRadiusEnd=4).encode(y=alt.Y("revenue:Q", title="Revenue ($)"))
    + monthly.mark_line(color="#eb6834", strokeWidth=2.5).encode(y="avg_3m:Q")
).properties(title="Monthly revenue against its three-month average")

Altair layered chart: light blue monthly revenue bars from about $40K to $87K with an orange three-month average line rising to about $83K in August 2026

Two layers added with +: bars and a moving average. Invented data.

+ layers two charts on the same axes (alt.layer(a, b) does the same). frame=[-2, 0] averages each month with the two before it.

5. Faceted small multiples

facet = alt.Chart(df).mark_line().encode(
    x=alt.X("yearmonth(order_date):T", title=None, axis=alt.Axis(format="%b %y", tickCount=4)),
    y=alt.Y("sum(revenue):Q", title="Revenue ($)"),
).properties(width=250, height=120).facet(
    facet=alt.Facet("region:N", title=None), columns=2
).properties(title="Monthly revenue, one chart per region")

Four small Altair line charts of monthly revenue, one each for East, North, South and West, on a shared scale; West peaks at about $34K in August 2026

Small multiples with .facet(): one chart per region on a shared y axis. Invented data.

The four panels share a y scale, so West's August 2026 spike (about $34,100) reads as the biggest month of any region.

6. An interactive chart: a brush, a filter and tooltips

Drag across the months in the top chart and the bars below show only those months. Hover a bar for its numbers.

brush = alt.selection_interval(encodings=["x"])
months = alt.Chart(df).mark_bar().encode(
    x=alt.X("yearmonth(order_date):T", title=None, axis=alt.Axis(format="%b %y")),
    y=alt.Y("sum(revenue):Q", title="Revenue ($)"),
    color=alt.when(brush).then(alt.value("#2a78d6")).otherwise(alt.value("#cde2fb")),
).add_params(brush).properties(height=150, title="Drag across the months to filter the regions")
regions = alt.Chart(df).mark_bar(cornerRadiusEnd=4).encode(
    x=alt.X("sum(revenue):Q", title="Revenue in the selected months ($)"),
    y=alt.Y("region:N", sort="-x", title=None),
    tooltip=[alt.Tooltip("region:N", title="Region"), alt.Tooltip("sum(revenue):Q", format="$,.0f", title="Revenue"),
             alt.Tooltip("count():Q", title="Orders")],
).transform_filter(brush).properties(height=140)
(months & regions).save("06-interactive.html", inline=True)

The saved Altair HTML in Chrome: May to October 2026 brushed in the monthly revenue bars, the region bars below filtered to those months, and a tooltip on West showing Revenue $128,505 and Orders 455

Our interactive chart open in Chrome, with May to October 2026 selected and a tooltip on West. Invented data.

This is the docs' grammar of interaction. A parameter (selection_interval) captures the drag. A condition (alt.when(...).then(...).otherwise(...)) colours the selected bars. A filter (transform_filter(brush)) cuts the second chart to the selection. & stacks the charts vertically and | puts them side by side. We checked the tooltip against pandas: West's May to October 2026 orders total $128,505 across 455 orders.

Connect any database. Ask in plain English.

Start free →

Save an Altair chart: HTML, PNG, SVG, PDF

You want Code What we got
Interactive web page chart.save("chart.html") 1,074 KB for chart 6; Vega loads from a CDN, so it needs a connection
Page that works offline chart.save("chart.html", inline=True) 1,950 KB; the JavaScript is inside
Image chart.save("chart.png", scale_factor=2) 105-451 KB per chart above
Vector or print chart.save("chart.svg"), "chart.pdf" Also through vl-convert
The spec itself chart.save("chart.json") or chart.to_json() 1,072 KB for chart 1, data included

PNG, SVG, PDF and inline=True need vl-convert, which the docs say "does not require any external dependencies". PNGs default to 72 pixels per inch; ppi=200 raises the resolution and scale_factor=2 doubles the size.

Most of chart 6's 1,074 KB is data: every column of all 4,734 orders is inside the page. The same bar chart as example 1, built from four pre-summed rows (df.groupby("category", as_index=False)["revenue"].sum()), has a 1 KB spec. Ours from the raw file was 1,072 KB.

The 5,000-row limit: MaxRowsError and how to fix it

Our sample is just under the limit. A file with twice the rows isn't:

big = pd.concat([df, df.assign(order_date=df["order_date"] + pd.DateOffset(years=2))])   # 9,468 rows
scatter = alt.Chart(big).mark_circle(size=12).encode(x="order_date:T", y="revenue:Q")
scatter.to_dict()   # what displaying the chart in a notebook calls
altair.utils.data.MaxRowsError: The number of rows in your dataset (9468) is greater than the maximum allowed (5000).
 
Try enabling the VegaFusion data transformer which raises this limit by pre-evaluating data
transformations in Python.
    >> import altair as alt
    >> alt.data_transformers.enable("vegafusion")
 
Or, see https://altair-viz.github.io/user_guide/large_datasets.html for additional information
on how to plot large datasets.

Altair scatter plot of all 4,734 invented orders by date and order value, dense below $400 with thinner bands up to about $1,800

A scatter of every order: 4,734 rows, just under the 5,000-row default. Invented data.

The docs say the limit exists so you "think carefully about how large datasets are handled", since every row goes into the page. We tried the fixes on the 9,468 rows and measured the page each one made:

Fix Code Result
Aggregate first big.groupby(pd.Grouper(key="order_date", freq="MS"))["revenue"].sum() 48 rows, 5 KB page
Fewer columns alt.Chart(big[["order_date", "revenue"]]) Still MaxRowsError: the limit counts rows
VegaFusion alt.data_transformers.enable("vegafusion") Scatter 573 KB (unused columns dropped); a monthly line from 9,468 rows, 8 KB
Data in a file alt.data_transformers.enable("json") 2 KB page plus a 2,168 KB JSON file that must travel with it
Switch the check off alt.data_transformers.disable_max_rows() 2,143 KB page

We measured the pages with chart.to_html(), and VegaFusion's with chart.save(). Three things we found that the docs don't spell out:

  • chart.save() doesn't raise. Its override_data_transformer argument defaults to True, and the save then runs with the check off and the default transformer, so the 9,468-row scatter saved as a 2,143 KB file without a word, and the json transformer had no effect on it.
  • VegaFusion needed pyarrow. With pip install vegafusion alone, the first save failed with ImportError: `Import pyarrow` failed. Installing pyarrow fixed it; altair[all] includes it.
  • VegaFusion's 100,000-row cap applied only when we set it. The docs say charts "will work with datasets containing up to 100,000 rows". A 118,350-row scatter went through enable("vegafusion") with no error; with enable("vegafusion", max_rows=100_000) it raised MaxRowsError.

Aggregating first also makes the smallest page by far: 5 KB against 2,143 KB. Pandas groupby covers the patterns.

Altair vs matplotlib vs Plotly

Altair 6.3 matplotlib 3.11 Plotly 7.1
How you write it Declare columns, marks and encodings Draw on a figure and its axes, step by step Build a figure object in Python
What renders it Vega-Lite, in the browser Python plotly.js, in the browser
Interaction Selections, conditions, filters, tooltips, widgets "interactive figures that can zoom, pan, update" The point of it: "interactive, publication-quality graphs"
Static images vl-convert, which "does not require any external dependencies" Built in, "many file formats" Kaleido 1.0+, which needs Chrome installed

Pick matplotlib for print and papers where every pixel matters. Pick Plotly for hover-heavy charts and Dash apps. Pick Altair when you want small multiples, layers and linked selections in a few lines. Plotly vs matplotlib and the best Python visualization libraries go further; types of charts helps choose the chart itself, and our chart maker comparison covers tools that need no code.

Altair charts in a Fastero notebook

When the chart is for a team, it has to live somewhere they can open. Fastero is an AI and data platform where people and AI agents work together on a team's data:

  • In a Fastero notebook an Altair chart draws in the cell's output, and Pin to Dashboard keeps it as the same chart on a dashboard (shipped 19 November 2026).
  • A SQL cell runs on one of the workspace's database connections with its stored credentials and lands in Python as a pandas DataFrame named after the cell, ready for alt.Chart.
  • Notebooks and their cron schedules are on the Free plan.
  • Colleagues sign in to see the work, and viewers are free on every plan.

A SQL cell in a Fastero notebook reading the sample sales database through a workspace connection into a variable named monthly, with its result table below

A Fastero notebook whose SQL cell reads a database connection; the rows arrive in Python as a DataFrame. Sample data.

FAQ

Is Altair free?

Yes. Vega-Altair is open source; PyPI lists it under the BSD licence, and it installs with pip install altair.

What is the difference between Altair and Vega-Lite?

Vega-Lite is a JSON grammar for charts that runs in the browser. Altair is the Python library that writes Vega-Lite for you; chart.to_json() shows the spec it made.

How do I save an Altair chart as a PNG?

Install vl-convert-python, then call chart.save("chart.png"). Add scale_factor=2 for a bigger image or ppi=200 for more pixels per inch; the default is 72.

How do I fix MaxRowsError in Altair?

Aggregate the data in pandas before charting it, so the chart gets dozens of rows rather than thousands. Otherwise enable the VegaFusion data transformer (install pyarrow too), write the data to a separate file with the json transformer, or switch the check off:

alt.data_transformers.disable_max_rows()

Is Vega-Altair related to Altair Engineering?

No. The project's docs say "The Vega-Altair open-source project is not affiliated with Altair Engineering, Inc."

What Python version does Altair need?

Altair 6.3.0 needs Python 3.11 or later, per PyPI; it dropped Python 3.10 in that release. We ran it on Python 3.14.3.

Sources

Read on 20 November 2026:

Ready to try it yourself?

Connect your database, ask questions in plain English, and get live dashboards — in under 2 minutes. No credit card required.

Follow Fastero on LinkedIn for new articles and examples.