当 x 轴为时间轴时,使用 xOffset 具有多个条形的条形图?

问题描述 投票:0回答:1

这是一个小例子:

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

如果我设置

x="Date:N"
,那么该示例的行为就像我想要的那样,但没有 x 轴时间格式的好处:

enter image description here

有什么方法可以让

xOffset
x="Date:T"
的情况下工作吗?

python vega-lite altair
1个回答
0
投票

如果您使用序数或名义数据类型,则可以提供

timeUnit
来获取日期格式。根据您使用的数据类型,有很多选项。

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

© www.soinside.com 2019 - 2024. All rights reserved.