Altair 数据聚合

red*_*ire 4 python charts altair

我试图在 Altair 上绘制以下内容: x = 每日时间戳 y = 记录数,因为数据是名义数据而不是定量数据

当我尝试按月或季度汇总 x 时,是否可以将 y 显示为每天的平均记录数而不是总和?

chart = alt.Chart(data).mark_bar().encode(
    x = alt.X('Date:T'),
    y = alt.Y('count(Name):Q'),
    color = alt.Color('descriptor:N')
)
chart
Run Code Online (Sandbox Code Playgroud)

当我尝试做的时候

chart = alt.Chart(data).mark_bar().encode(
    x = alt.X('month(Date):T'),
    y = alt.Y('count(Name):Q'),
    color = alt.Color('descriptor:N')
)
chart
Run Code Online (Sandbox Code Playgroud)

它按月总数汇总,是否可以计算每月计数的平均值?

jak*_*vdp 7

您可以使用 Altair 的转换语法应用多个聚合。对于您的图表,您可以执行以下操作:

alt.Chart(data).transform_aggregate(
    daily_count = 'count(Name)',
    groupby=['Date', 'descriptor']
).mark_bar().encode(
    x = alt.X('month(Date):O'),
    y = alt.Y('mean(daily_count):Q'),
    color = alt.Color('descriptor:N')
)
Run Code Online (Sandbox Code Playgroud)