这是一个小例子:
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
如果我设置
x="Date:N"
,那么该示例的行为就像我想要的那样,但没有 x 轴时间格式的好处:
有什么方法可以让
xOffset
在x="Date:T"
的情况下工作吗?
如果您使用序数或名义数据类型,则可以提供
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