如何使用d3-contour绘制简单2D等高线图
D3.js 2D等高线图实现方案
前置准备
使用D3 v7及以上版本,内置d3-contour模块,低版本D3需要单独引入对应版本的d3-contour依赖包。
完整实现代码
1. 数据格式转换
d3-contour要求输入为扁平化一维数组,先处理你的二维5行4列原始数据:
// 原始二维数组:5行4列 const rawData = [[0.01, 0.012, 0.034, 0.024],[0.01, 0.012, 0.034, 0.024],[0.01, 0.012, 0.034, 0.024],[0.01, 0.012, 0.034, 0.024],[0.01, 0.012, 0.034, 0.024]]; // 转换为d3-contour要求的一维数组 const flatData = rawData.flat(); // 网格尺寸:宽为列数4,高为行数5 const gridWidth = 4, gridHeight = 5;
2. 等高线生成器配置
// 生成等高线几何数据,thresholds控制等高线数量,可按需调整 const contours = d3.contours() .size([gridWidth, gridHeight]) .thresholds(10) (flatData);
3. 画布与比例尺配置
// 实际画布尺寸 const svgWidth = 500, svgHeight = 400; const margin = {top: 20, right: 20, bottom: 20, left: 20}; // 创建SVG容器 const svg = d3.select("body") .append("svg") .attr("width", svgWidth + margin.left + margin.right) .attr("height", svgHeight + margin.top + margin.bottom) .append("g") .attr("transform", `translate(${margin.left}, ${margin.top})`); // 颜色映射规则,可替换为你需要的配色 const colorScale = d3.scaleLinear() .domain(d3.extent(flatData)) .range(["#f7fbff", "#08306b"]); // 坐标映射:把小网格坐标映射到实际画布尺寸 const pathGenerator = d3.geoPath() .projection(d3.geoIdentity().scale(Math.min(svgWidth/gridWidth, svgHeight/gridHeight)));
4. 绘制等高线
// 绘制等高线填充区域 svg.selectAll(".contour") .data(contours) .enter() .append("path") .attr("class", "contour") .attr("d", pathGenerator) .attr("fill", d => colorScale(d.value)) .attr("stroke", "#ffffff") .attr("stroke-width", 0.5;
常见运行失败排查
- 尺寸参数不匹配:
contours.size()的参数必须是[列数, 行数],和你输入的二维数组维度完全对应,否则会报错 - 数值范围与阈值不匹配:如果你的数值差异很小,可适当减少
thresholds的数值,避免等高线过于密集无法显示 - 版本兼容问题:D3 v6及以下版本未内置d3-contour,需要单独引入对应版本的依赖
- 你的示例数据所有行数值完全一致,生成的等高线会是垂直分割线,替换为带梯度变化的数组即可得到和参考图类似的渐变效果
内容的提问来源于stack exchange,提问作者AndiAna
相关产品推荐
相关产品推荐

