【问题标题】:Altair heatmap with dropdown variable selector带有下拉变量选择器的 Altair 热图
【发布时间】:2021-05-18 19:56:34
【问题描述】:

考虑这个玩具数据集:

import pandas as pd
import altair as alt

df = pd.read_json('https://cdn.jsdelivr.net/npm/vega-datasets@v1.29.0/data/cars.json')
df = df.groupby(['Origin', 'Year'])[['Miles_per_Gallon', 'Weight_in_lbs', 'Displacement']].mean().reset_index()
df = pd.melt(df, id_vars=['Origin', 'Year'], value_vars=['Miles_per_Gallon', 'Weight_in_lbs', 'Displacement'])
df.head()


    Origin  Year    variable    value
0   Europe  1970-01-01  Miles_per_Gallon    25.20
1   Europe  1971-01-01  Miles_per_Gallon    28.75
2   Europe  1972-01-01  Miles_per_Gallon    22.00
3   Europe  1973-01-01  Miles_per_Gallon    24.00
4   Europe  1974-01-01  Miles_per_Gallon    27.00

我想制作一个热图,我可以在其中选择要对填充颜色进行编码的变量。从文档来看,这似乎可行,因为下拉选择器会根据所选变量对 df 进行子集化:

dropdown = alt.binding_select(options=list(df.variable.drop_duplicates()))
alt.Chart(df).mark_rect().encode(
    x='Origin:N', 
    y='Year:T', 
    color='value:Q',
).add_selection(
    alt.selection_single(fields=['variable'], bind=dropdown, name='Select')
)

这会生成一个热图,但选择器没有效果。选择用于热图颜色编码的变量的正确方法是什么?

【问题讨论】:

    标签: python altair


    【解决方案1】:

    您需要将选择分配给变量名称,并通过add_selection 将其添加到图表中,并通过transform_filter 将其绑定以过滤数据。

    dropdown = alt.binding_select(options=list(df.variable.drop_duplicates()))
    selection = alt.selection_single(fields=['variable'], bind=dropdown, name='Select')
    
    alt.Chart(df).mark_rect().encode(
        x='Origin:N', 
        y='Year:T', 
        color='value:Q',
    ).add_selection(
        selection
    ).transform_filter(
        selection
    )
    

    【讨论】:

      猜你喜欢
      • 2021-09-28
      • 2020-09-18
      • 1970-01-01
      • 2011-06-21
      • 2019-10-04
      • 2011-03-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多