能否通过点击操作重新排序Vega-Lite堆叠条形图的堆叠层级?
实现点击图例调整堆叠条形图层级并添加折线图层
需求说明
- 已设置独立的自定义圆形图例,点击可选中特定天气类型
- 核心需求:点击图例时,将选中的天气类别移至堆叠条形图底部,便于清晰观察其计数趋势
- 额外优化:添加折线图层,突出展示选中类别的月度计数变化趋势
效果预览

实现代码
{ "$schema": "https://vega.github.io/schema/vega-lite/v5.json", "data": {"url": "data/seattle-weather.csv"}, "vconcat": [ { "title": "Combined", "layer": [ { "mark": { "type": "bar", "cornerRadiusTopLeft": 1, "cornerRadiusTopRight": 1 }, "encoding": { "x": {"timeUnit": "month", "field": "date", "type": "ordinal"}, "y": { "aggregate": "count", "stack": "zero" }, "color": { "field": "weather", "legend": null, "sort": { "field": "weather", "order": "descending", "condition": { "selection": "weather_selected", "sort": {"field": "is_selected", "order": "ascending"} } } }, "opacity": { "condition": {"selection": "weather_selected", "value": 1}, "value": 0.1 } } }, { "mark": {"type": "line", "color": "#000", "strokeWidth": 2}, "encoding": { "x": {"timeUnit": "month", "field": "date", "type": "ordinal"}, "y": { "aggregate": "count", "field": "weather" } }, "transform": [ { "filter": {"selection": "weather_selected"} } ] } ], "transform": [ { "calculate": "datum.weather == weather_selected.weather ? 0 : 1", "as": "is_selected" } ] }, { "width": 27, "height": 10, "align": "center", "mark": {"type": "circle", "size": 200}, "encoding": { "column": { "field": "weather", "type": "nominal", "header": {"title": null} }, "color": { "field": "weather", "scale": {"range": ["#1f77b4", "#ff7f0e", "#2ca02c", "#d62728"]} }, "opacity": { "condition": {"selection": "weather_selected", "value": 1}, "value": 0.1 } } } ], "selection": { "weather_selected": { "type": "single", "fields": ["weather"], "empty": "none", "init": {"weather": "sun"} } }, "config": {} }
关键修改点
- 全局统一
weather_selected选择器,避免局部选择器冲突 - 通过
transform计算is_selected字段,控制color的排序逻辑,让选中类别移至堆叠底部 - 使用
layer组合条形图与折线图,折线图仅展示选中类别的计数趋势 - 优化透明度交互,保持选中类别高亮,其他类别淡化
内容的提问来源于stack exchange,提问作者APB Reports
相关产品推荐
相关产品推荐

