TimeUnit#

TimeUnit 转换用于在 Altair 中离散化日期和时间。与上面讨论的AggregateBin一样,它们既可以定义为编码的一部分,也可以定义为顶层转换。

以下是可用的时间单位

  • "year", "yearquarter", "yearquartermonth", "yearmonth", "yearmonthdate", "yearmonthdatehours", "yearmonthdatehoursminutes", "yearmonthdatehoursminutesseconds"

  • "quarter", "quartermonth"

  • "month", "monthdate"

  • "date" (月份中的日期,即 1 - 31)

  • "day" (星期几,即 周一 - 周五)

  • "hours", "hoursminutes", "hoursminutesseconds"

  • "minutes", "minutesseconds"

  • "seconds", "secondsmilliseconds"

  • 毫秒

编码中的 TimeUnit#

任何时间字段定义都可以包含 timeUnit 参数来离散化时间数据。

例如,这里我们绘制了 2010 年西雅图每小时温度测量值组成的数据集

import altair as alt
from vega_datasets import data

temps = data.seattle_temps.url

alt.Chart(temps).mark_line().encode(
    x='date:T',
    y='temp:Q'
)

由于大量数据点挤压在短时间内,图表过于密集;我们可以通过离散化使其更清晰一些,例如按月离散化并仅绘制月平均温度

alt.Chart(temps).mark_line().encode(
    x='month(date):T',
    y='mean(temp):Q'
)

注意,默认情况下 timeUnit 输出是一个连续量;如果您希望它是一个分类量,您可以指定有序 (O) 或名义 (N) 类型。这在绘制条形图或其他离散图表类型时非常有用

alt.Chart(temps).mark_bar().encode(
    x='month(date):O',
    y='mean(temp):Q'
)

可以在单个图表中组合多个时间单位,以产生有趣的数据视图;例如,这里我们提取月份和日期,以展示西雅图全年温度的概况

alt.Chart(temps).mark_rect().encode(
    alt.X('date(date):O').title('day'),
    alt.Y('month(date):O').title('month'),
    color='max(temp):Q'
).properties(
    title="2010 Daily High Temperatures in Seattle (F)"
)

作为转换的 TimeUnit#

有时将 timeUnit 指定为顶层转换很方便,尤其是在该值可能被重用的情况下。使用 Chart.transform_timeunit() 方法可以最方便地完成此操作。例如

alt.Chart(temps).mark_line().encode(
    alt.X('month:T').axis(format='%b'),
    y='mean(temp):Q'
).transform_timeunit(
    month='month(date)'
)

请注意,因为 timeUnit 在此处不属于编码通道的一部分,通常需要添加轴格式化器以确保轴标签合适。

转换选项#

transform_timeunit() 方法基于 TimeUnitTransform 类构建,该类具有以下选项

点击显示表格

属性

类型

描述

as

FieldName

写入 timeUnit 值的输出字段。

field

FieldName

应用时间单位的数据字段。

timeUnit

anyOf(TimeUnit, TimeUnitTransformParams)

时间单位。