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:
- Create a DataFrame containing x, x2, y, and y2 values for each rectangle. section 7.5.3 section 9.2.1
- Pass the DataFrame to alt.Chart(...).mark_rect(), then encode x and y with x2 and y2 as the opposite vertices. section 7.5.3 section 9.2.1
- Adjust color and opacity for emphasis; remove axes when the rectangle is a diagram element rather than a data axis. section 7.5.3 section 9.2.1
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
