import altair as alt
from IPython.display import HTML
from sklearn.datasets import make_blobs
import pandas as pd
Encoding point Z-order in Altair charts
altair
Just making some data here for demonstration.
= [[1, 1], [-1, -1], [1, -1]]
centers = make_blobs(n_samples=2000, centers=centers, cluster_std=1)
X, y
= (
df_points =['a', 'b'])
pd.DataFrame(X, columns=pd.Categorical(y, ordered=True, categories=[0, 1, 2]))
.assign(label
)
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).
= alt.Axis(titleFontSize=18, titlePadding=20, titleFontWeight='normal', labelFontSize=12)
axis = {'range': ['lightgray','lightgray','steelblue']}
scale
= alt.Chart(df_points, width=400, height=400).mark_point(fillOpacity=0.25, strokeOpacity=0.75, size=50).encode(
c =alt.X('a', axis=axis),
x=alt.Y('b', axis=axis),
y=(
color'label:N')
alt.Color(**scale)
.scale(='top-left', titleFontSize=16, labelFontSize=12)
.legend(orient
),=alt.Fill('label:N').scale(**scale),
fill1=alt.Order('label', sort='ascending'),
order
)
with alt.renderers.enable("default"):
= c._repr_mimebundle_()["text/html"]
html
= html.replace("display: flex;", "display: flex;\njustify-content: center;")
s
display(HTML(s))
- 1
-
This is the
order
encoding. It forces the blue points to the top.