Vega-Lite分层折线图如何设置不同线条颜色?
Vega-Lite分层折线图颜色区分问题解决
问题原因
确实是分层(layer)结构导致的——Vega-Lite会自动合并同类型编码(比如这里的stroke)的比例尺,把两个图层的stroke字段合并到同一个定义域(domain)中,而你只配置了单一颜色的范围(range),所以两条线会共用同一颜色。
解决方案
有两种简单可行的方法实现预期效果:
方法1:直接在mark属性中指定颜色
不需要通过encoding的stroke字段控制,直接给每个图层的mark设置固定stroke颜色,这样不会触发比例尺共享:
"layer": [ { "name": "Production CY", "mark": {"type": "line", "tooltip": true, "stroke": "black"}, "encoding": { "x": {"field": "Financial Month Nr", "type": "ordinal"}, "y": { "field": "Production CY", "type": "quantitative", "title": "Production (ton)" } } }, { "name": "Production PY", "mark": {"type": "line", "tooltip": true, "stroke": "red"}, "encoding": { "x": {"field": "Financial Month Nr", "type": "ordinal"}, "y": { "aggregate": "sum", "field": "Production PY", "type": "quantitative", "axis": null } } } ]
方法2:设置独立的stroke比例尺
如果仍需通过encoding的stroke字段配置,给每个图层的stroke编码添加scale: {"independent": true},强制禁用比例尺共享:
"layer": [ { "name": "Production CY", "mark": {"type": "line", "tooltip": true}, "encoding": { "x": {"field": "Financial Month Nr", "type": "ordinal"}, "y": { "field": "Production CY", "type": "quantitative", "title": "Production (ton)" }, "stroke": { "field": "Production CY Legend", "scale": {"range": ["black"], "independent": true}, "legend": {"title": ""} } } }, { "name": "Production PY", "mark": {"type": "line", "tooltip": true}, "encoding": { "x": {"field": "Financial Month Nr", "type": "ordinal"}, "y": { "aggregate": "sum", "field": "Production PY", "type": "quantitative", "axis": null }, "stroke": { "field": "Production PY Legend", "scale": {"range": ["red"], "independent": true}, "legend": {"title": ""} } } } ]
效果说明
两种方法都能实现上年数据折线为红色、当年数据折线为黑色的区分效果,匹配你的预期图表样式。
内容的提问来源于stack exchange,提问作者Deston
相关产品推荐
相关产品推荐

