This code creates a bar chart binned by month.
# Load libraries
import pandas as pd
import altair as alt
from vega_datasets import data
# Load data
df = data.seattle_weather()
# Create chart
alt.Chart(df).mark_bar().encode(
x='month(date):T',
y='mean(temp_max)')
Is is possible to bin by every "n" months? For example, each bar would be the data from two months (Jan+Feb, Mar+Apr, June+July... etc).

The only built-in multi-month binning is the quarter time unit; for example:
alt.Chart(df).mark_bar().encode(
x='quarter(date):O',
y='mean(temp_max)'
)

If you wanted something more customized, you can use a calculate transform including an appropriate vega expression to group results as you'd like. For example:
alt.Chart(df).transform_calculate(
group='month(datum.date) < 4 ? "Jan-Apr" : month(datum.date) < 8 ? "May-Aug" : "Sep-Dec"'
).mark_bar().encode(
x='group:O',
y='mean(temp_max)'
)

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With