如何在Altair图表中指定type数据可视化(无需过滤DataFrame)
解决方案
不用提前过滤原始DataFrame的话,有两种实用方法可以实现只显示指定type的折线:
方法一:静态筛选指定类型
直接在Altair的图表链中使用transform_filter方法,在绘图阶段筛选出目标type值,无需修改原始数据:
import altair as alt import pandas as pd dt = pd.DataFrame({'date': ['2022', '2023', '2024'], 'type':['t1', 't2', 't3'], 'value': [1, 2, 3]}) fig = alt.Chart(dt).mark_line().encode( x=alt.X('date:T'), y=alt.Y('value:Q'), color=alt.Color('type:N') ).transform_filter( # 这里指定要显示的type列表 alt.FieldOneOfPredicate(field='type', oneOf=['t1', 't2']) ) fig.show()
这个方法会直接在绘图时过滤掉不需要的type数据,最终只显示你指定的折线。
方法二:交互式动态选择类型
如果需要灵活切换显示的type,可以添加一个交互式选择器,通过点击图例就能控制显示/隐藏对应折线:
import altair as alt import pandas as pd dt = pd.DataFrame({'date': ['2022', '2023', '2024'], 'type':['t1', 't2', 't3'], 'value': [1, 2, 3]}) # 定义多选选择器,默认选中t1和t2 type_selector = alt.selection_multi(fields=['type'], bind='legend', init=[{'type': 't1'}, {'type': 't2'}]) fig = alt.Chart(dt).mark_line().encode( x=alt.X('date:T'), y=alt.Y('value:Q'), color=alt.Color('type:N'), # 选中的折线显示完全不透明,未选中的隐藏 opacity=alt.condition(type_selector, alt.value(1), alt.value(0)) ).add_selection( type_selector ) fig.show()
这种方式更灵活,不需要修改代码就能切换显示的type,适合需要频繁调整展示内容的场景。
内容的提问来源于stack exchange,提问作者OcMaRUS
相关产品推荐
相关产品推荐

