如何用Deneb(Vega Lite)创建带横竖线及轴标签的折线图
Deneb(Vega Lite)带轴标签的折线+横竖线规范
以下是调整后的规范,解决了横竖线与坐标轴交点的自定义标签问题,同时优化了数据类型处理:
{ "data": { "values": [ {"date": "2010-01-01", "price": 300, "source": "A"}, {"date": "2011-01-01", "price": 315, "source": "A"}, {"date": "2012-01-01", "price": 285, "source": "A"}, {"date": "2013-01-01", "price": 345, "source": "A"}, {"date": "2014-01-01", "price": 365, "source": "A"}, {"date": "2015-01-01", "price": 385, "source": "A"}, {"date": "2016-01-01", "price": 415, "source": "A"}, {"date": "2017-01-01", "price": 400, "source": "A"}, {"date": "2018-01-01", "price": 380, "source": "A"}, {"date": "2019-01-01", "price": 270, "source": "A"}, {"date": "2020-01-01", "price": 325, "source": "A"}, {"date": "2021-01-01", "price": 345, "source": "A"}, {"date": "2022-01-01", "price": 360, "source": "A"}, {"date": "2010-01-01", "price": 385, "source": "B"}, {"date": "2015-01-01", "price": 385, "source": "B"}, {"date": "2015-01-01", "price": 385, "source": "C"}, {"date": "2015-01-01", "price": 0, "source": "C"} ] }, "width": 500, "height": 250, "layer": [ // 主折线(A源) { "mark": "line", "transform": [{"filter": "datum.source === 'A'"}], "encoding": { "x": {"field": "date", "type": "temporal"}, "y": {"field": "price", "type": "quantitative"} } }, // 水平线(B源) { "mark": {"type": "line", "strokeDash": [3, 1]}, "transform": [{"filter": "datum.source === 'B'"}], "encoding": { "x": {"field": "date", "type": "temporal"}, "y": {"field": "price", "type": "quantitative"} } }, // 垂直线(C源) { "mark": {"type": "line", "strokeDash": [3, 1]}, "transform": [{"filter": "datum.source === 'C'"}], "encoding": { "x": {"field": "date", "type": "temporal"}, "y": {"field": "price", "type": "quantitative"} } }, // 水平线与Y轴交点标签 { "mark": { "type": "text", "align": "right", "baseline": "middle", "dx": -10, "fontSize": 12 }, "transform": [ {"filter": "datum.source === 'B'"}, {"aggregate": [{"op": "max", "field": "price", "as": "y_val"}], "groupby": []} ], "encoding": { "y": {"field": "y_val", "type": "quantitative"}, "text": {"value": "基准价格"}, "color": {"value": "#333"} } }, // 垂直线与X轴交点标签 { "mark": { "type": "text", "align": "center", "baseline": "top", "dy": 10, "fontSize": 12 }, "transform": [ {"filter": "datum.source === 'C'"}, {"aggregate": [{"op": "max", "field": "date", "as": "x_val"}], "groupby": []} ], "encoding": { "x": {"field": "x_val", "type": "temporal"}, "text": {"value": "关键节点"}, "color": {"value": "#333"} } } ] }
关键调整说明:
- 将
price字段的字符串值改为数值类型,避免可视化时的类型解析错误 - 添加两个独立的
text标记层实现轴标签:- 水平线标签:通过聚合获取水平线的Y值,在Y轴旁添加自定义文本,用
dx控制水平偏移距离 - 垂直线标签:通过聚合获取垂直线的X值,在X轴下方添加自定义文本,用
dy控制垂直偏移距离
- 水平线标签:通过聚合获取水平线的Y值,在Y轴旁添加自定义文本,用
- 把全局的
width和height移到根层级,避免在子图层重复定义
内容的提问来源于stack exchange,提问作者DataWrangler1980
相关产品推荐
相关产品推荐

