You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Altair的selection功能通过选中基因高亮其所属的整个聚类

实现选中基因高亮对应全聚类的代码调整方案

核心逻辑是通过Altair的transform_lookup转换,将下拉选中基因对应的聚类标签匹配到全量数据行,再按聚类标签匹配判断是否高亮,具体修改如下:

第一步:调整选择器定义(可选优化)

保留原有下拉绑定逻辑,可添加empty参数控制无选择时的默认显示效果:

input_dropdown = alt.binding_select(options=list(pd.unique(df_samp['CGI'])), name='gene')
# empty='all'表示未选择时显示所有聚类,可改为empty='none'默认全不显示
selection = alt.selection_single(fields=['CGI'], bind=input_dropdown, empty='all')

第二步:修改UMAP散点图逻辑

移除原有不完整的transform_filter,添加lookup转换匹配选中基因对应的聚类,按聚类匹配控制透明度:

# Create UMAP scatter plot
UMAP_chart = alt.Chart(df_samp).mark_circle(size=6).encode(
    x='UMAP_1',
    y='UMAP_2',
    color = alt.Color('UPGMA_label:N', legend = None),
    # 匹配当前行聚类和选中基因的聚类,一致则完全显示,否则透明
    opacity=alt.condition(
        datum.UPGMA_label == datum.selected_cluster,
        alt.value(1.0), 
        alt.value(0.0)
    )                         
).properties(height=500, width=500
# 从选择器中匹配选中CGI对应的UPGMA_label,作为新字段selected_cluster添加到所有行
).transform_lookup(
    lookup='CGI',
    from_=alt.LookupSelection(selection, 'CGI', ['UPGMA_label']),
    as_=['selected_cluster']
)

第三步:修改趋势折线图逻辑

和散点图做相同的lookup转换和透明度判断:

# Create pattern line plot
graph_cols = ['CGI', 'week0', 'week1', 'week2', 'week4', 'week6', 'week8', 'UPGMA_label']
graph_df = df_samp[graph_cols].melt(['CGI', 'UPGMA_label'], var_name='week', value_name='data')

pattern_chart = alt.Chart(graph_df).mark_line().encode(
    x='week',
    y='data',
    color= alt.Color('CGI:N', legend = None),
    # 同散点图逻辑,按聚类匹配控制显示
    opacity=alt.condition(
        datum.UPGMA_label == datum.selected_cluster,
        alt.value(1.0), 
        alt.value(0.0)
    )
).properties(width=500
# 同样添加lookup转换
).transform_lookup(
    lookup='CGI',
    from_=alt.LookupSelection(selection, 'CGI', ['UPGMA_label']),
    as_=['selected_cluster']
)

第四步:拼接图表逻辑不变

chart = alt.hconcat(pattern_chart, UMAP_chart).add_selection(selection)

修改后选择任意基因时,会自动匹配该基因所属的聚类,高亮该聚类下所有基因的散点和趋势线。


内容的提问来源于stack exchange,提问作者haidan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 10:54:02