altair charts
altair charts
basic setup
import altair as alt
import pandas as pd
# Sample data
data = pd.DataFrame({
"x": [1, 2, 3, 4, 5],
"y": [10, 20, 15, 30, 25]
})
simple line chart
bar chartscatter plot
area chart
encoding with titles & types
chart = alt.Chart(data).mark_line().encode(
x=alt.X("x:Q", title="X Axis"),
y=alt.Y("y:Q", title="Y Axis")
)
chart
add color encodings
data["category"] = ["A", "B", "A", "B", "A"]
chart = alt.Chart(data).mark_point(size=100).encode(
x="x",
y="y",
color="category:N"
)
chart
tooltip
sorting values
aggregation ( mean, sum )
Grouped bar chart
stacked bar chart
chart = alt.Chart(data).mark_bar().encode(
x="x:O",
y="y:Q",
color="category:N"
).properties(
width=400
)
chart
faceting ( small multiples )
interactive ( zoom and pan )
Filtering Data :
chart = alt.Chart(data).transform_filter(
alt.datum.y > 15
).mark_point().encode(
x="x",
y="y"
)
chart
Layer multiple charts
line = alt.Chart(data).mark_line(color="blue").encode(
x="x",
y="y"
)
points = alt.Chart(data).mark_point(color="red").encode(
x="x",
y="y"
)
chart = line + points
chart
add chart title
chart = alt.Chart(data).mark_line().encode(
x="x",
y="y"
).properties(
title="My Altair Chart"
)
chart
save chart png / html