Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"?

like image 601
bzm3r Avatar asked Mar 04 '26 23:03

bzm3r


1 Answers

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

like image 197
kgoodrick Avatar answered Mar 06 '26 13:03

kgoodrick



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!