Altair Cheat Sheet Python: Data Visualization Reference

Altair Cheat Sheet Python

01 Build a chart


1. Import + general pattern

import altair as alt
chart = (
    alt.Chart(data).mark_…()
    .encode(x=…, y=…, color=…)
    .transform_…(…).properties(…)
    .interactive()
)

2. Choose a chart type

mark_bar   bars / aggregated comparison
mark_line   trends over an ordered axis
mark_circle   scatter plots
mark_area   filled trends / totals
mark_rect   heat maps
mark_arc   pie or donut charts
mark_boxplot   distribution summaries
mark_geoshape   geographic shapes

Also: mark_point(), mark_tick(), mark_text(), mark_rule(), mark_square(), mark_errorbar().

3. Field data types

Append a code to a field name. Describes meaning of data, not just type.
:Q quantitative – numeric magnitude
:N nominal – unordered category
:O ordinal – ordered category
:T temporal – date or time
:G GeoJSON geographic data

4. Encode fields

Short form is compact; channel objects add options.
.encode(
    x=alt.X(“Horsepower:Q”, title=”Horsepower”),
    y=”Miles_per_Gallon:Q”, color=”Origin:N”,
    size=”Acceleration:Q”, shape=”Origin:N”,
    opacity=alt.value(0.7),
    tooltip=[“Name:N”, “Origin:N”]
)

x / y   horizontal / vertical position
color   fill or stroke by field
size   mark area or line width
shape   symbol category
opacity   transparency
tooltip   values shown on hover
row / column   small-multiple layout

5. Axes, scales, & titles

x=alt.X(

    “Horsepower:Q”,
    scale=alt.Scale(domain=[0, 250]),
    axis=alt.Axis(title=”Horsepower”, format=”.0f”))
# scale=alt.Scale(zero=False); axis=None hides axis
.properties(
    title=alt.Title(“Horsepower vs. Fuel Efficiency”,
                          subtitle=”Automobile dataset”),
    width=600, height=400)

Note: May need to use explicit types if Altair infers the wrong visual meaning.

02 Transform & Polish


6. Bin values & histogram

alt.Chart(cars).mark_bar().encode(
    x=alt.X(“Horsepower:Q”, bin=True),
    y=”count()”)
# bin=alt.Bin(maxbins=20) sets bin count

7. Aggregate

alt.Chart(cars).mark_bar().encode(
    x=”Origin:N”, y=”mean(Miles_per_Gallon):Q”)
# mean, median, sum, min, max, count
# alt.Y(“Miles_per_Gallon:Q”, aggregate=”mean”)

8. Sort categories

x=alt.X(“Origin:N”, sort=”-y”)
# “ascending” / “descending”; “-x” / “-y”
# [“USA”, “Europe”, “Japan”] = custom order

9. Filter rows

.transform_filter(
    (alt.datum.Horsepower > 100) &
    (alt.datum.Origin == “USA”))
# | is OR; ~ is NOT

10. Calculate a new field

.transform_calculate(
    Efficiency=”datum.Miles_per_Gallon / “
                      “datum.Horsepower”
).encode(y=”Efficiency:Q”)

ORDER MATTERS
Transforms run in sequence. Filter before aggregating if only filtered rows should contribute.

11. Common mark options

.mark_circle(size=70, opacity=0.7)
.mark_line(point=True, strokeWidth=2)
.mark_bar(cornerRadius=3)
.mark_arc(innerRadius=50) # donut
.mark_text(align=”left”, dx=4)

12. Complete scatter plot

chart = (
    alt.Chart(cars)
        .mark_circle(size=70, opacity=0.7)
        .encode(
            x=alt.X(“Horsepower:Q”, title=”Horsepower”),
            y=alt.Y(“Miles_per_Gallon:Q”, title=”Miles per gallon”),
            color=”Origin:N”,
            tooltip=[“Name:N”, “Origin:N”,
                          “Horsepower:Q”, “Miles_per_Gallon:Q”])
        .properties(title=”Horsepower vs. MPG”,
                        width=600, height=400)
    .interactive()
)

13. Global styling

styled = (chart
    .configure_view(stroke=None)
    .configure_axis(grid=False)
    .configure_legend(titleFont2)
    .configure_title(font6))

03 Interact & Share


14. Zoom & pan

chart.interactive()
# Interval selection bound to x/y scales

15. Click to highlight

pick = alt.selection_point(fields=[“Origin”])
chart = (
    alt.Chart(cars).mark_circle().encode(
        x=”Horsepower:Q”, y=”Miles_per_Gallon:Q”,
        color=alt.condition(pick, “Origin:N”,
                                        alt.value(“lightgray”)))
    .add_params(pick)
)

16. Brush one chart; filter another

brush = alt.selection_interval()
base = alt.Chart(cars)
points = base.mark_circle().encode(
x=”Horsepower:Q”, y=”Miles_per_Gallon:Q”
).add_params(brush)
bars = base.mark_bar().encode(
x=”Origin:N”, y=”count()”
).transform_filter(brush)
points & bars

SELECTION TYPES
selection_point() selects discrete marks; selection_interval() selects a rectangular
region.

17. Combine charts

a | b                 horizontal concatenation
a & b               vertical concatenation
a + b               layer marks in one view
alt.layer(a,b)    explicit layering

18. Layer a regression line

points = alt.Chart(cars).mark_circle().encode(
    x=”Horsepower:Q”, y=”Miles_per_Gallon:Q”)
line = points.transform_regression(
          “Horsepower”, “Miles_per_Gallon”
).mark_line(color=”firebrick”)
points + line

19. Facet into small multiples

alt.Chart(cars).mark_circle().encode(
    x=”Horsepower:Q”, y=”Miles_per_Gallon:Q”,
         column=”Origin:N”)
# Or: chart.facet(column=”Origin:N”)

20. Save & Export

chart.save(“chart.html”) # interactive
chart.save(“chart.png”) # static
chart.save(“chart.svg”)
chart.save(“chart.pdf”)
chart.save(“chart.json”) # specification
# Image/offline: pip install “altair[save]”