如何在Vega-Lite中按图例顺序堆叠条形图
解决Vega-Lite堆叠条形图顺序与图例不一致的问题
实现方法
要让堆叠条形从下到上的顺序与图例(数据顺序)保持一致为["first","Second","third"],需调整以下关键配置:
指定颜色字段的排序规则
在encoding的color属性中添加sort配置,明确指定目标顺序,确保图例与数据分组顺序匹配:"color": { "field": "category", "type": "nominal", "sort": ["first", "Second", "third"] }设置堆叠顺序与排序规则匹配
在encoding的y属性中,将stack的order设为"ascending"(默认堆叠顺序为降序,会反转自定义排序),让条形从下到上按指定顺序堆叠:"y": { "field": "value", "type": "quantitative", "stack": { "order": "ascending" } }
完整配置示例
将上述配置整合到你的图表spec中,示例如下:
{ "data": { /* 你的数据源配置 */ }, "mark": "bar", "encoding": { "x": {"field": "x", "type": "nominal"}, "y": { "field": "value", "type": "quantitative", "stack": {"order": "ascending"} }, "color": { "field": "category", "type": "nominal", "sort": ["first", "Second", "third"] } } }
调整后,堆叠条形的顺序会从下到上依次为first、Second、third,与图例顺序完全一致。
内容的提问来源于stack exchange,提问作者Mohit
相关产品推荐
相关产品推荐

