Skip to main content
 首页 » 编程设计

python之具有不同 x 和 y 编码的 Altair 选择

2024年11月24日852php

我正在尝试根据传入的数据框和变量列表动态生成要在网页上显示的图表列表。 master_chart 应该有一个时间元素,然后 master_chart 上的间隔选择将影响在其他生成的图表上“突出显示”或选择的内容。然而,当我这样做时,所有其他生成的图表上的选择在彼此之间起作用,但主图表上的选择没有被其他图表注册。当我将其他图表的 x 变量更改为时间元素时,主图表上的选择起作用并改变了所有其他图表上数据点的颜色,反之亦然。但是,当我将 x 编码更改为所需值时,主图表上的任何选择都会像这样取消选择辅助图表上的所有点(好吧,我无法上传图片,因为我没有足够的声誉,但链接在这里 https://ibb.co/56LSTwW ).我希望它能在其他图表上显示那些时间的所有数据,但它似乎不起作用。我是否误解了复合牵牛星间隔选择的功能。任何想法将不胜感激。

后期编辑: 编辑后,我用 seattle-weather vega 数据集重现了这个例子。我的目标是拥有一组交互式图表,其中一个图表上的选择将突出显示其他图表上的数据点。该函数返回一个包含一个图表的列表,该列表呈现在我网页上的 Jinja 模板中。我已经能够在网页上呈现许多不同类型的图表,所以我知道我的问题是基于我对 Altair 的理解。当我在具有相同 Y 轴的三个图表中的任何一个上进行选择时,它会选择所有其他图表上的点,包括 master_chart,例如 https://ibb.co/ssDwGZ6 。但是,当我在顶部图表 master_chart 上进行选择时,其他任何图表 https://ibb.co/pRwDbF4 都没有选择。这是否与其他图表的 for-loop 结构有关,还是因为主图表的 x 和 y 编码与其他图表不同?任何建议将不胜感激。

import altair as alt 
import pandas as pd 
from vega_datasets import data 
 
var_dframe = data.seattle_weather() 
primary_x = "precipitation" 
param_list = ["precipitation", "temp_max", "temp_min", "wind"] 
 
def make_charts(var_dframe, primary_x, param_list): 
    other_charts_list = [] 
    compound_chart_list = [] 
    the_brush = alt.selection(type='interval', resolve='global') 
    master_chart = alt.Chart(var_dframe).mark_point(filled=True).encode( 
        x= alt.X("date:T"), 
        y= primary_x +":Q", 
        color= alt.condition(the_brush, alt.value('blue'), alt.value('grey')) 
    ).add_selection(the_brush) 
    for item in (param_list[1:]): 
        new_chart = alt.Chart(var_dframe).mark_point( 
            filled=True, 
        ).encode( 
            x= alt.X("%s:Q" % item), 
            y= alt.Y("temp_max:Q"), 
            color = alt.condition(the_brush, alt.value('blue'), alt.value('gray')) 
        ).add_selection(the_brush) 
        other_charts_list.append(new_chart) 
 
    compound_chart = master_chart 
    for chart in other_charts_list: 
        compound_chart = compound_chart & chart 
 
    compound_chart_list.append(compound_chart.to_json()) 
    return(compound_chart_list) 
 
 

请您参考如下方法:

这种奇怪的行为是由于 Vega-Lite 中的一个已知错误造成的:Interval selection on temporal data returns empty selection .解决方法是为每个图表面板添加时间编码;在这里,您可以通过在代码片段中创建的每个 new_chart 对象中添加 detail="date:T" 作为编码来实现此目的。