liveBook · Manning

Mark_rect()

As explained in Data Storytelling with Altair and AI

mark_rect() is an Altair API method that creates rectangular marks in a chart.

mark_rect() is an Altair API method for drawing rectangular marks. Use it to highlight a time range or construct visual roadmap steps, making an intended insight easier to see. section 7.5.3 section 9.2.1

Build a rectangle by preparing coordinates and then encoding its boundaries:

Highlighting a sales decline

A rectangle spanning 1992–1998, from y=0 to a value above the chart maximum, marks the period of declining salmon sales. Pair it with mark_text() to explain the associated fish-health issues. section 7.5.3

Building a visualized roadmap

Generate three rectangles parametrically for “Online Campaign,” “Influencers Engagement,” and “Social Media Promotion.” Combine them with labels and connecting lines to show next steps. section 9.2.1

Listing 7.17 The rectangle
N = 100000000           #1
y = df['AMOUNT'].max() + N

rect_df = pd.DataFrame({'x': [1992], 
            'x2': [1998],
            'y' : [0],
            'y2': [y]
        })

rect = alt.Chart(rect_df).mark_rect(
    color='lightgrey',
    opacity=0.5
).encode(
    x='x:O',
    x2='x2:O',
    y= 'y:Q',
    y2= 'y2:Q'
)

Inspect a complete mark_rect() definition for a highlighted period, including DataFrame coordinates, ordinal x encoding, quantitative y encoding, color, and opacity. section 7.5.3

Listing 9.2 Drawing the rectangles
import altair as alt 

rect = alt.Chart(df_rect).mark_rect(
    color='#80C11E',
    opacity=0.2
).encode(
    x=alt.X('x:Q', axis=None),
    y=alt.Y('y:Q', axis=None),
    x2='x2:Q',
    y2='y2:Q'
).properties(
    width=700,
    height=100,
    title=alt.TitleParams(
        text=['What can we do next?'],
        fontSize=20,
        offset=10
    )
)

Inspect a diagram-style rectangle chart with quantitative coordinates, hidden axes, custom dimensions, opacity, and a title. section 9.2.1

How Data Storytelling with Altair and AI covers it

How deep it goes
Explains coordinate preparation, boundary encoding, styling, axis handling, and composition, but defers the method's underlying rendering internals.
Examples
Uses a 1992–1998 sales-decline highlight and three parametrically positioned roadmap rectangles.
What it assumes
Assumes basic Python, pandas DataFrame creation, and Altair chart encoding while demonstrating rectangle coordinates from zero.
What you can do after
Build it from scratch by preparing rectangle coordinates and encoding their boundaries in an Altair chart.
How it connects
Connects mark_rect() with Altair, pandas DataFrame, encoding channels, mark_text(), mark_line(), and layered or concatenated charts.

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.