liveBook · Manning

Mark_rule()

As explained in Data Storytelling with Altair and AI

mark_rule() is an Altair API method that specifies rule marks, such as horizontal or vertical reference lines.

Altair’s mark_rule() adds rule marks—horizontal or vertical reference lines—that give charts a clear comparison point or visual guide. section 4.5.2 section 6.3.2

Use mark_rule() to make chart comparisons easier:

  • Create a horizontal baseline, such as a red line at 50% improvement, to show which values exceed a target. section 4.5.2
  • Create vertical guide lines from numeric x-values, then style them with color, stroke width, and opacity. section 6.3.2
  • Layer the rule chart with other chart elements using the + operator. section 4.5.2 section 6.3.2

Horizontal baseline

A 50% baseline can be built from a small DataFrame and encoded on y: line = alt.Chart(pd.DataFrame({'y': [50]})).mark_rule(color='red').encode(y='y'); chart = chart + line. The resulting chart makes the sports performing above the baseline immediately visible. section 4.5.2

Listing 4.17 The generated code to create a baseline
line = alt.Chart(pd.DataFrame({'y': [50]})).mark_rule(color='red').encode(y='y')
chart = chart + line

Inspect the complete generated code for a red horizontal rule at y=50 and its layered combination with the original chart. section 4.5.2

How Data Storytelling with Altair and AI covers it

How deep it goes
Shows Python construction with DataFrames, encodings, styling, and layering, but defers broader axis refinement.
Examples
Uses a 50% sports baseline and white vertical guides at 20, 40, 60, 80, and 100 in a meal bar chart.
What it assumes
Assumes Python, pandas, and an existing Altair chart while demonstrating rule construction through concrete examples.
What you can do after
Apply it via Altair to add comparison baselines or vertical reading guides to bar charts.
How it connects
Connects rule marks with Altair charts, encodings, DataFrames, chart layering, bar charts, and visual decluttering.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Data Storytelling with Altair and AI. The section links point to the parts of the book it draws on.