Encoding point Z-order in Altair charts

altair
Author

ChuckPR

Published

December 13, 2024

import altair as alt
from IPython.display import HTML
from sklearn.datasets import make_blobs
import pandas as pd

Just making some data here for demonstration.

centers = [[1, 1], [-1, -1], [1, -1]]
X, y = make_blobs(n_samples=2000, centers=centers, cluster_std=1)

df_points = (
    pd.DataFrame(X, columns=['a', 'b'])
    .assign(label=pd.Categorical(y, ordered=True, categories=[0, 1, 2]))
)

df_points.head()
a b label
0 -1.214458 -1.672904 2
1 0.271734 -1.012541 2
2 2.086623 2.339706 0
3 1.918859 0.593477 2
4 -0.617844 -1.212739 1

The order encoding in combination with mark_point allows you to control the z-order of points in the chart. You can set the sorting order of categorical data via categories in pd.Categorical (see above).

axis = alt.Axis(titleFontSize=18, titlePadding=20, titleFontWeight='normal', labelFontSize=12)
scale = {'range': ['lightgray','lightgray','steelblue']}

c = alt.Chart(df_points, width=400, height=400).mark_point(fillOpacity=0.25, strokeOpacity=0.75, size=50).encode(
    x=alt.X('a', axis=axis),
    y=alt.Y('b', axis=axis),
    color=(
        alt.Color('label:N')
        .scale(**scale)
        .legend(orient='top-left', titleFontSize=16, labelFontSize=12)
    ),
    fill=alt.Fill('label:N').scale(**scale),
1    order=alt.Order('label', sort='ascending'),
)

with alt.renderers.enable("default"):
    html = c._repr_mimebundle_()["text/html"]

s = html.replace("display: flex;", "display: flex;\njustify-content: center;")

display(HTML(s))
1
This is the order encoding. It forces the blue points to the top.