Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bin by multiple months in altair?

Tags:

python

altair

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).

enter image description here

like image 661
max Avatar asked Oct 22 '25 01:10

max


1 Answers

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)'
)

enter image description here

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)'
)

enter image description here

like image 105
jakevdp Avatar answered Oct 24 '25 15:10

jakevdp



Donate For Us

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