Search code examples
vegavega-litealtair

Vega lite/Altair parsing date specified in quarters


I have a dataset with data in the form 2000Q1, 2000Q2 etc. I would like to use this as a temporal variable.

How can I achieve this in Vega Lite/Altair?


Solution

  • You can use timeParse in combination with string functions as part of a calculate transform.

    timeParse uses d3 time formats, which unfortunately don't support quarters natively, so we need to do some string manipulations.

    It's not very elegant, but here's the Vega Lite

    "transform": [
        {
          "as": "date",
          "calculate": "timeParse(replace(replace(replace(replace(datum.yearquarter, 'Q1', '02'), 'Q2', '05'),  'Q3', '08'), 'Q4', '11'), '%Y%m')"
        }
      ]
    

    In Altair, this looks like this:

    chart = alt.Chart(url
    ).transform_calculate(date = "timeParse(replace(replace(replace(replace(datum.yearquarter, 'Q1', '02'), 'Q2', '05'),  'Q3', '08'), 'Q4', '11'), '%Y%m')"
    ).mark_bar().encode(
    y = 'sum(value):Q',
    x = 'date:T'
    )