pythonvega-litealtair

Bar chart with multiple bars using xOffset, when the x-axis is temporal?


Here's a small example:

import altair as alt
import polars as pl

source = pl.DataFrame(
    {
        "Category": list("AAABBBCCC"),
        "Value": [0.1, 0.6, 0.9, 0.7, 0.2, 1.1, 0.6, 0.1, 0.2],
        "Date": [f"2024-{m+1}-1" for m in range(3)] * 3,
    }
).with_columns(pl.col("Date").str.to_date())

bars = alt.Chart(source).mark_bar().encode(
    x=alt.X("Date:T"),
    xOffset="Category:N",
    y="Value:Q",
    color="Category:N",
)

bars

example output

If I set x="Date:N", then the example behaves as I'd like, but without the benefits of temporal formatting for the x-axis:

enter image description here

Is there any way in which I can have xOffset work for the case where x="Date:T"?


Solution

  • If you use the ordinal or nominal data type, you can supply a timeUnit to get date formatting. There are many options depending on what kind of data you are working with.

    import altair as alt
    import polars as pl
    
    source = pl.DataFrame(
        {
            "Category": list("AAABBBCCC"),
            "Value": [0.1, 0.6, 0.9, 0.7, 0.2, 1.1, 0.6, 0.1, 0.2],
            "Date": [f"2024-{m+1}-1" for m in range(3)] * 3,
        }
    ).with_columns(pl.col("Date").str.to_date())
    
    bars = alt.Chart(source.to_pandas()).mark_bar().encode(
        x=alt.X("Date:O", timeUnit="yearmonthdate"),
        xOffset="Category:N",
        y="Value:Q",
        color="Category:N",
    )
    
    bars
    

    enter image description here