如何用Vega Spec实现量子比特六边形热力图?
六边形热力图Vega实现修正
原代码问题分析
- 六边形尺寸计算错误:
hexWidth和hexHeight的计算公式无效,导致偏移量为0,无法实现交错排列 - 三角函数参数错误:
sin(60)未转换为弧度,Vega的sin函数默认接受弧度值 - 交错偏移逻辑错误:行偏移的判断条件和偏移量不符合六边形网格的排列规则
- 坐标刻度类型不合适:使用
point类型刻度无法精准控制六边形的排列间距
修正后的完整代码
{ "$schema": "https://vega.github.io/schema/vega/v5.json", "width": 500, "height": 300, "padding": {"left": 30, "top": 10, "right": 10, "bottom": 30}, "signals": [ { "name": "hexRadius", "value": 35 }, { "name": "hexWidth", "update": "2 * hexRadius * sin(PI/3)" }, { "name": "hexHeight", "update": "1.5 * hexRadius" } ], "data": [ { "name": "heatmapData", "values": [ {"row": 1, "column": 1, "metric": 0.01}, {"row": 2, "column": 1, "metric": 0.02}, {"row": 3, "column": 1, "metric": 0.03}, {"row": 1, "column": 2, "metric": 0.04}, {"row": 2, "column": 2, "metric": 0.05}, {"row": 3, "column": 2, "metric": 0.06}, {"row": 1, "column": 3, "metric": 0.07}, {"row": 2, "column": 3, "metric": 0.08}, {"row": 3, "column": 3, "metric": 0.09} ] } ], "scales": [ { "name": "x", "type": "linear", "domain": {"data": "heatmapData", "field": "column"}, "range": [0, {"signal": "width - 40"}], "nice": true }, { "name": "y", "type": "linear", "domain": {"data": "heatmapData", "field": "row"}, "range": [{"signal": "height - 40"}, 0], "nice": true }, { "name": "color", "type": "linear", "domain": [0.01, 0.09], "range": {"scheme": "purples"} } ], "axes": [ { "orient": "left", "scale": "y", "title": "行", "tickCount": 3 }, { "orient": "bottom", "scale": "x", "title": "列", "tickCount": 3 } ], "marks": [ { "type": "path", "from": {"data": "heatmapData"}, "encode": { "enter": { "path": { "signal": "'M' + 0 + ',' + (-hexRadius) + ' ' +\n" + " 'L' + (hexRadius * sin(PI/3)) + ',' + (-hexRadius/2) + ' ' +\n" + " 'L' + (hexRadius * sin(PI/3)) + ',' + (hexRadius/2) + ' ' +\n" + " 'L' + 0 + ',' + hexRadius + ' ' +\n" + " 'L' + (-hexRadius * sin(PI/3)) + ',' + (hexRadius/2) + ' ' +\n" + " 'L' + (-hexRadius * sin(PI/3)) + ',' + (-hexRadius/2) + ' Z'" }, "x": { "signal": "scale('x', datum.column) + (datum.row % 2 === 1 ? hexWidth/2 : 0)" }, "y": { "signal": "scale('y', datum.row)" }, "fill": {"scale": "color", "field": "metric"}, "stroke": {"value": "white"}, "strokeWidth": {"value": 1} } } }, { "type": "text", "from": {"data": "heatmapData"}, "encode": { "enter": { "x": { "signal": "scale('x', datum.column) + (datum.row % 2 === 1 ? hexWidth/2 : 0)" }, "y": { "signal": "scale('y', datum.row)" }, "text": {"field": "metric"}, "align": {"value": "center"}, "baseline": {"value": "middle"}, "fill": {"value": "black"}, "fontSize": {"value": 12} } } } ] }
关键修改说明
- 六边形尺寸修正:
hexWidth设为2 * hexRadius * sin(PI/3)(即√3*radius),hexHeight设为1.5 * hexRadius,符合正六边形的几何比例 - 三角函数修正:用
PI/3替代60,确保传入sin函数的是弧度值 - 交错排列逻辑:奇数行的x坐标偏移
hexWidth/2,实现六边形网格的交错布局 - 刻度类型调整:将x、y刻度改为
linear类型,更灵活地控制六边形的位置和间距 - 布局优化:调整padding和range范围,避免图形超出画布
内容的提问来源于stack exchange,提问作者Farhan Azam
相关产品推荐
相关产品推荐

