时间和分钟作为 Altair 图中跨越一天以上的标签

Hours and minutes as labels in Altair plot spanning more than one day

我正在尝试在 Altair 中创建时间范围跨越几天的时间序列图的 Vega-Lite 规范。因为在我的例子中,哪一天是哪一天会很清楚,我想通过让标签采用 '%H:%M' 形式来减少轴标签中的噪音,即使这会导致标签不明显。

这是一些示例数据;我的实际数据有五分钟的分辨率,但我想这在这里不会太重要:

import altair as alt
import numpy as np
import pandas as pd

# Create data spanning 30 hours, or just over one full day
df = pd.DataFrame({'time': pd.date_range('2018-01-01', periods=30, freq='H'),
                   'data': np.arange(30)**.5})

通过使用其他微不足道的 yearmonthdatehoursminutes 转换,我得到以下结果:

alt.Chart(df).mark_line().encode(x='yearmonthdatehoursminutes(time):T', 
y='data:Q')

现在,我的目标是去掉横轴上标签中的日期,使它们变成类似 ['00:00', '03:00', ..., '21:00', '00:00', '03:00'] 或任何最合适的间距。

仅使用 hoursminutes 作为转换的幼稚方法是行不通的,因为它会分箱实际数据:

alt.Chart(df).mark_line().encode(x='hoursminutes(time):T', y='data:Q')

那么,有没有一种声明式的方式来做到这一点?最终,可视化将利用选择来定义水平轴限制,因此使用 Axis 明确指定标签似乎没有吸引力。

这实际上可以通过在 Axis 中指定 format 来轻松实现:

alt.Chart(df).mark_line().encode(x=alt.X('time:T', axis=alt.Axis(format='%H:%M')), y='data:Q')

为了扩展@fuglede 的回答,在 Altair 中有两个不同的日期和时间概念。

时间格式 允许您指定时间在轴上的显示方式;它们看起来像这样:

chart.encode(
    x=alt.X('time:T', axis=alt.Axis(format='%H:%M'))
)

Altair 使用来自 d3-time-format.

的格式代码

时间单位 可让您指定数据的分组方式,它们还会调整默认时间格式以匹配。它们看起来像这样:

chart.encode(
    x=alt.X('time:T', timeUnit='hoursminutes')
)

或通过 shorthand:

chart.encode(
    x='hoursminutes(time):T'
)

列出了可用的时间单位 here

如果您只想调整坐标轴格式,请使用时间格式。如果您想根据时间跨度进行分组(即按年、月、小时等对数据进行分组),请使用时间单位。这方面的例子出现在 Altair 文档中,例如Altair 示例库中的 Seattle Weather Heatmap