Grouped bar chart by month in Altair

Viewed 37

I have a data set with monthly values, and I want to group the bars by month. However, in my current data set the grouped bars either 1) show up in alphabetical order (Apr, Aug, Dec...) which is obviously wrong, or 2) show the entire date-time label (April 1, 2021), which means the labels cover each other up. Ideally I would like the groups to be labeled with this format:

Jun 2021, Jul, Aug, Sep, Oct, Nov, Dec, Jan 2022, Feb, Mar, Apr, May, Jun

How can I set this up? Changing the code to

'month(date):T'

gets me part way there, BUT it combines the data from Jan 2020 + Jan 2021 + Jan 2022 all in one column labeled "Jan". Here is my full code...

import pandas as pd
from vega_datasets import data
import altair as alt

df = data.crimea().melt(id_vars='date')
source = df

chart = alt.Chart(source).mark_bar().encode(
   column='date:T',
   x=alt.X('variable:O', axis=alt.Axis(ticks=False, labels=False, title='')),
   y=alt.Y('value:Q', axis=alt.Axis(grid=False, title='')),
   color=alt.Color('variable:O', scale=alt.Scale(range=['#FFDB58', '#CACACA', '#911C2A']), legend=alt.Legend(title="", orient="right")),

).properties(width=20, height=450, title=alt.TitleParams(
        ['Source: vega-datasets.'],
        baseline='bottom',
        orient='bottom',
        anchor='start',
        dy=40, dx=0
    ))

title = (
    alt.Chart()
    .mark_text(text='Crimes by type', x=0, y='height')
)

subtitle = alt.Chart(
    {"values": [{"text": "Instances of crimes per month"}]}
).mark_text().encode(
    text="text:N"
)



alt.vconcat(
    title,
    subtitle,
    chart
).configure_view(
    stroke=None,
)

enter image description here

And subbing 'month(date):T' gives the following:

enter image description here

1 Answers
Related