1

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 Answers1

0

You can use combination of time groupings, so 'yearmonth(date):T' would group by both year and month. More info in the Vega-Lite docs.

joelostblom
  • 43,590
  • 17
  • 150
  • 159
  • Thanks, but that makes the year show up on every single label. I only want the year to label to show up once per year, i.e. "Jan 2021, Feb, Mar, Apr...". Is there any workaround? – granadallama Aug 23 '22 at 14:46
  • 1
    @granadallama You can change the formatting of the axis by using `alt.Axis(format=)`, e.g. as here https://altair-viz.github.io/user_guide/transform/timeunit.html?highlight=format#timeunit-as-a-transform. I am not sure if you can set it to only include the years sometimes, but you can set it to never, or always include it. You might want to ask a new general Vega-Lite question for you new query – joelostblom Aug 24 '22 at 19:33