使用间隔选择:操纵 Altair 的各个编码通道的聚合所采用的内容

Using interval selection: manipulate what is taken into aggregation of individual encoding channels of altair

我正在制作一个 XY 散点图,其中两个轴都显示聚合数据。 对于这两个变量,我想在下面的两个小图表中进行间隔选择,我可以在其中沿着 x 轴刷牙以设置范围。

然后应该使用选择来过滤每个聚合操作单独考虑的内容。

cars 数据集为例,假设我要查看马力与排量的关系。但不是每辆车:相反,我按 Origin 汇总(求和)。此外,我创建了两个完全平均 HP 和位移随时间变化的图,我在其中添加了间隔选择,以便能够设置两个不同的时间范围。 这是它应该是什么样子的示例,尽管选择功能尚未达到预期。

下面是生成它的代码。请注意,我在那里留下了一些评论部分,这些部分显示了我已经尝试过但不起作用的内容。 transform_calculate 的想法来自这个 GitHub issue。但我不知道如何使用提取的边界值来更改 x 和 y 通道聚合中包含的内容。双 transform_window 都没有带我去任何地方。 transform_bin 在这里有用吗?怎么样?

基本上,我想要的是:当brush1从1972年到1975年,brush2从1976年到1979年,我想要散点图绘制每个国家在1972年,1973年和1974年的HP总和针对每个国家/地区从 1976 年、1977 年和 1978 年开始的位移总和(对于我的情况,我不需要确切的日期格式,Year 在这里也可能是整数)。

import altair as alt
from vega_datasets import data
cars = data.cars.url

brush1 = alt.selection(type="interval", encodings=['x'])
brush2 = alt.selection(type="interval", encodings=['x'])


scatter = alt.Chart(cars).mark_point().encode(
    x = 'HP_sum:Q',
    y = 'Dis_sum:Q',
    tooltip = 'Origin:N'
).transform_filter(  # Ok, I can filter the whole data set, but that always acts on both variables (HP and displacement) together... -> not what I want.
    brush1 | brush2
).transform_aggregate(
    Dis_sum = 'sum(Displacement)',
    HP_sum = 'sum(Horsepower)',
    groupby = ['Origin']
# ).transform_calculate(  # Can I extract the selection boundaries like that? And if yes: how can I use these extracts to calculate the aggregationsof HP and displacement?
#     b1_lower='(isDefined(brush1.x) ? (brush1.x[0]) : 1)',
#     b1_upper='(isDefined(brush1.x) ? (brush1.x[1]) : 1)',
#     b2_lower='(isDefined(brush2.x) ? (brush2.x[0]) : 1)',
#     b2_upper='(isDefined(brush2.x) ? (brush2.x[1]) : 1)',
# ).transform_window(  # Maybe instead of calculate I can use two window transforms...??
#     conc_sum = 'sum(conc)',
#     frame = [brush1.x[0],brush1.x[1]],  # This will not work, as it sets the frame relative (back- and foreward) to each datum (i.e. sliding window), I need it to correspond to the entire data set
#     groupby=['sample']
# ).transform_window(
#     freq_sum = 'sum(freq)',
#     frame = [brush2.x[0],brush2.x[1]],  # ...same problem here
#     groupby=['sample']
)

range_sel1 = alt.Chart(cars).mark_line().encode(
    x = 'Year:T',
    y = 'mean(Horsepower):Q'
).add_selection(
    brush1
).properties(
    height = 100
)

range_sel2 = alt.Chart(cars).mark_line().encode(
    x = 'Year:T',
    y = 'mean(Displacement):Q'
).add_selection(
    brush2
).properties(
    height = 100
)


scatter & range_sel1 & range_sel2

Interval selection cannot be used for aggregate charts yet in Vega-Lite. The error behavior have been updated in a recent PR to Vega-Lite to show a helpful message.

不确定我是否正确理解了您的要求,这看起来接近您想要的吗? (刚刚在垂直串联图的顶部添加了参数选择)

Vega Editor