# Altair Bar Charts and Line Charts: The Basics

> Altair bar chart and line chart examples: mark_bar() and mark_line(), sorting, horizontal bars, value labels, grouped bars with xOffset, stacked and 100% stacked bars, and multi-series lines.

Source: https://www.pythoncharts.com/altair/altair-bar-line-charts/ | Published: 2026-11-26 | Author: Alex Scott | Category: Altair | Tags: altair, bar chart, line chart, grouped bar chart, stacked bar chart, vega-lite

In Altair you make a bar chart with `mark_bar()` and a line chart with `mark_line()`, then say which columns go on `x`, `y`, and `color` inside `encode()`. Switching between the two is mostly a matter of changing the mark. This post covers the variations you'll need most often, using Altair 6.2.

## Quick Example

This draws one line per column value, with a point at each month and a tooltip on hover.

```python
import altair as alt
import numpy as np
import pandas as pd

# Sample data: a year of monthly checkouts at a public library.
rng = np.random.default_rng(20)
months = pd.date_range("2025-01-01", periods=12, freq="MS")
base = {"Print": 5200, "Ebook": 2400, "Audiobook": 1500}
growth = {"Print": -60, "Ebook": 90, "Audiobook": 190}
summer = np.array([0, 0, 0, 0, 100, 700, 900, 600, 0, 0, 0, -200])

df = pd.concat([
    pd.DataFrame({
        "month": months,
        "format": name,
        "checkouts": (base[name] + growth[name] * np.arange(12)
                      + summer * base[name] / 5200
                      + rng.normal(0, 130, 12)).round().astype(int),
    })
    for name in base
])

chart = alt.Chart(df, width="container", height=300).mark_line(point=True).encode(
    x=alt.X("yearmonth(month):T", title=None),
    y=alt.Y("checkouts:Q", title="Checkouts"),
    color=alt.Color("format:N", title="Format"),
    tooltip=[alt.Tooltip("yearmonth(month):T", title="Month"), "format",
             alt.Tooltip("checkouts:Q", format=",")],
)
chart
```

![Interactive Altair line chart of monthly library checkouts in 2025: print peaks in summer while audiobooks and ebooks climb through the year](https://www.pythoncharts.com/altair/altair-bar-line-charts/images/altair-bar-line-quick.png)

The data is in long format: one row per month and format, with the format name in its own column. That's the shape Altair expects. If your series are in separate columns, reshape with `df.melt()` first. `yearmonth(month)` tells Altair to treat each date as a month, and `width="container"` stretches the chart to the width of the page.

## Make a Basic Bar Chart

Use `mark_bar()`, put the category on one axis, and aggregate the other. `sum(checkouts)` adds up the twelve months for each format, so you don't need a pandas `groupby` first.

```python
totals = alt.Chart(df, width=420, height=280).mark_bar().encode(
    x=alt.X("format:N", sort="-y", title=None, axis=alt.Axis(labelAngle=0)),
    y=alt.Y("sum(checkouts):Q", title="Checkouts in 2025"),
)
totals
```

![Altair bar chart of 2025 library checkouts, with Print tallest, then Ebook, then Audiobook](https://www.pythoncharts.com/altair/altair-bar-line-charts/images/altair-bar-basic.png)

`sort="-y"` orders the bars from largest to smallest by the y value. Without it, categories are sorted alphabetically. You can also pass a list, such as `sort=["Print", "Ebook", "Audiobook"]`, to set the order yourself. `labelAngle=0` keeps the category names horizontal, since Altair rotates them by default.

## Horizontal Bar Chart With Value Labels

Swap the channels to get horizontal bars: the category goes on `y` and the number on `x`. For labels, add a `mark_text()` layer that shares the same encodings.

```python
genres = pd.DataFrame({
    "genre": ["Mystery", "Romance", "Science fiction", "Biography",
              "Children's picture books", "Cooking", "Graphic novels"],
    "checkouts": [9840, 8315, 4120, 3375, 11260, 2210, 5630],
})

base_bars = alt.Chart(genres, width=380, height=260).encode(
    x=alt.X("checkouts:Q", title=None, axis=None),
    y=alt.Y("genre:N", sort="-x", title=None),
)

labeled = (
    base_bars.mark_bar(color="#2a9d8f")
    + base_bars.mark_text(align="left", dx=4).encode(
        text=alt.Text("checkouts:Q", format=","))
).configure_view(stroke=None)
labeled
```

![Horizontal Altair bar chart of checkouts by genre, sorted with children's picture books first and cooking last, each bar labeled with its value](https://www.pythoncharts.com/altair/altair-bar-line-charts/images/altair-bar-horizontal.png)

Long category names are the main reason to go horizontal: they stay readable without rotation. `sort="-x"` sorts by bar length, `align="left"` with `dx=4` places each label just past the end of its bar, and `configure_view(stroke=None)` removes the border around the plot.

## Grouped Bar Chart With xOffset

To put bars side by side, map the grouping column to both `color` and `xOffset`. Here the quarters are on the x axis and each format gets its own bar within a quarter.

```python
df["quarter"] = "Q" + df["month"].dt.quarter.astype(str)
format_order = ["Print", "Ebook", "Audiobook"]

grouped = alt.Chart(df, width=480, height=280).mark_bar().encode(
    x=alt.X("quarter:N", title=None, axis=alt.Axis(labelAngle=0)),
    xOffset=alt.XOffset("format:N", sort=format_order),
    y=alt.Y("sum(checkouts):Q", title="Checkouts"),
    color=alt.Color("format:N", sort=format_order, title="Format"),
)
grouped
```

![Grouped Altair bar chart of quarterly checkouts, showing print falling after its summer quarter while audiobooks rise every quarter](https://www.pythoncharts.com/altair/altair-bar-line-charts/images/altair-bar-grouped.png)

Give `xOffset` and `color` the same `sort` list so the bar order matches the legend. `xOffset` was added in Altair 5; older tutorials use a `column` facet for this, which you no longer need.

## Stacked and 100% Stacked Bar Charts

Leave out `xOffset` and Altair stacks the colored segments. Set `stack="normalize"` on the y channel to show each segment as a share of its bar.

```python
stacked_base = alt.Chart(df, width=235, height=280).mark_bar().encode(
    x=alt.X("quarter:N", title=None, axis=alt.Axis(labelAngle=0)),
    color=alt.Color("format:N", sort=format_order, title="Format",
                    legend=alt.Legend(orient="top")),
    order=alt.Order("color_format_sort_index:Q"),
)

counts = stacked_base.encode(y=alt.Y("sum(checkouts):Q", title="Checkouts"))
shares = stacked_base.encode(
    y=alt.Y("sum(checkouts):Q", stack="normalize", title="Share of checkouts",
            axis=alt.Axis(format="%")))

(counts | shares)
```

![Two Altair stacked bar charts by quarter, one with checkout counts and one normalized to 100 percent, where the print share shrinks and the audiobook share grows](https://www.pythoncharts.com/altair/altair-bar-line-charts/images/altair-bar-stacked.png)

The `order` line makes the segments stack in the same order as `sort=format_order`, with Print at the bottom. Altair creates the `color_format_sort_index` field when you give the color channel a custom sort list. The counts chart shows how total volume changes, and the normalized chart shows the mix: audiobooks go from a small slice in Q1 to a much larger one in Q4.

## Style a Line Chart

Line options are arguments to `mark_line()`. `interpolate` changes how points are joined, `strokeWidth` sets the thickness, and `strokeDash` as an encoding gives each series its own dash pattern.

```python
styled = alt.Chart(df, width=480, height=280).mark_line(
    interpolate="monotone", strokeWidth=3
).encode(
    x=alt.X("yearmonth(month):T", title=None,
            axis=alt.Axis(format="%b", tickCount="month")),
    y=alt.Y("checkouts:Q", title="Checkouts", scale=alt.Scale(zero=False)),
    color=alt.Color("format:N", sort=format_order, title="Format"),
    strokeDash=alt.StrokeDash("format:N", sort=format_order, title="Format"),
)
styled
```

![Altair line chart with smooth lines, a different dash pattern for each format, and month abbreviations on the x axis](https://www.pythoncharts.com/altair/altair-bar-line-charts/images/altair-line-styled.png)

| Setting | What it does |
|---|---|
| `interpolate="monotone"` | smooth curve that doesn't overshoot the data points |
| `interpolate="step-after"` | holds each value until the next one, good for prices or inventory |
| `point=True` | adds a marker at every data point |
| `scale=alt.Scale(zero=False)` | lets the y axis start near the smallest value |

Starting a line chart's y axis above zero is usually fine, because readers compare slopes and positions. Keep bar charts at zero: the bar's length is the value.

## Label Lines Directly and Add a Reference Line

A label at the end of each line saves readers from looking back and forth to a legend. Filter to the last month with `transform_filter`, draw text there, and use `mark_rule()` for a horizontal reference.

```python
lines = alt.Chart(df, width=440, height=280).mark_line().encode(
    x=alt.X("yearmonth(month):T", title=None),
    y=alt.Y("checkouts:Q", title="Checkouts"),
    color=alt.Color("format:N", legend=None),
)

end_labels = lines.mark_text(align="left", dx=6, fontWeight="bold").encode(
    text="format:N"
).transform_filter(alt.datum.month >= alt.expr.toDate("2025-12-01T00:00"))

goal = alt.Chart(pd.DataFrame({"goal": [3000]})).mark_rule(
    strokeDash=[6, 4], color="gray"
).encode(y="goal:Q")
goal_text = goal.mark_text(align="left", dx=4, dy=-8, color="gray").encode(
    x=alt.value(0), text=alt.value("Digital goal: 3,000"))

lines + end_labels + goal + goal_text
```

![Altair line chart with each format named at the end of its line and a dashed horizontal goal line at 3,000 checkouts](https://www.pythoncharts.com/altair/altair-bar-line-charts/images/altair-line-labels.png)

Layers are combined with `+`, and later layers draw on top. `alt.value()` sets a fixed pixel position or constant instead of reading a column. There's more on this in [layering and concatenating Altair charts](https://www.pythoncharts.com/altair/altair-layer-concat-charts/).

## Bar Chart or Line Chart?

- **Bar chart** for comparing separate categories, or a few time periods where each total matters.
- **Line chart** for trends over many time points, especially with several series.
- **Grouped bars** for comparing series within each category. Past four or so series it gets crowded.
- **Stacked bars** when the total matters most and the parts are secondary.

## Practical Tips

- Type suffixes matter: `:N` (category), `:O` (ordered category), `:Q` (number), `:T` (date). A year stored as an integer usually wants `:O` on a bar chart.
- Aggregate in the encoding with `sum()`, `mean()`, `median()`, or `count()`. `count()` needs no column name.
- Altair refuses data over 5,000 rows by default. Aggregate in pandas first, or see [saving Altair charts and the row limit](https://www.pythoncharts.com/altair/save-altair-charts/).
- For axis titles, number formats, and label rotation, see [axis titles and formatting in Altair](https://www.pythoncharts.com/altair/altair-axis-titles-formatting/).

## Similar Topics

- [Interactive Selections and Brushing in Altair](https://www.pythoncharts.com/altair/altair-interactive-selections/)
- [Combine Multiple Altair Charts (Layering and Concatenation)](https://www.pythoncharts.com/altair/altair-layer-concat-charts/)
- [Set Custom Axis Titles and Formatting in Altair](https://www.pythoncharts.com/altair/altair-axis-titles-formatting/)
