基于D3开发带正负值、数据驱动高度的水平条形图
实现支持正负值的可变宽度水平条形图

<!DOCTYPE html> <meta charset="utf-8"> <!-- 引入D3.js库 --> <script src="https://d3js.org/d3.v6.js"></script> <!-- 创建用于放置图表的容器 --> <div id="my_dataviz"></div> <script> // 示例数据 // x值决定条形宽度与方向(负向左,正向右),y值决定条形高度占比 const data = [{ x: -5, y: 15, color: '#ff0000' }, // 高度占比15% { x: 7, y: 55, color: '#0000ff' }, // 高度占比55% { x: 3, y: 30, color: '#00ff00' }, // 高度占比30% ]; // 画布基础尺寸 const width = 500; const height = 300; // 边距设置 const margin = { top: 20, right: 20, bottom: 30, left: 40 }; // X轴线性比例尺 // 扩大1.25倍域范围,给条形两端留出空白 const x = d3.scaleLinear() .domain([d3.min(data, d => d.x * 1.25), d3.max(data, d => d.x * 1.25)]) .range([margin.left, width - margin.right]); // Y轴线性比例尺 // 基于y值的百分比范围设置域,实现高度比例缩放 const y = d3.scaleLinear() .domain([0, 100]) .range([height - margin.bottom, margin.top]); // 创建SVG画布 const svg = d3.select('body') .append('svg') .attr('width', width) .attr('height', height); // 绘制条形 svg.selectAll('rect') .data(data) .enter() .append('rect') // 负数条形从0点向左绘制,正数从0点向右绘制 .attr('x', d => x(Math.min(0, d.x))) // 基于y值设置条形顶部位置 .attr('y', d => y(d.y)) // 计算条形宽度:x值对应的坐标与0点坐标的绝对值 .attr('width', d => Math.abs(x(d.x) - x(0))) // 计算条形高度:0点y坐标与当前y值坐标的差值 .attr('height', d => y(0) - y(d.y)) // 设置条形颜色 .attr('fill', d => d.color); // 创建坐标轴 const xAxis = d3.axisBottom(x); const yAxis = d3.axisLeft(y) .ticks(5) .tickFormat(d => d + '%'); // 绘制X轴 svg.append('g') .attr('transform', `translate(0, ${height - margin.bottom})`) .call(xAxis); // 绘制Y轴 svg.append('g') .attr('transform', `translate(${margin.left}, 0)`) .call(yAxis); </script> </html>
内容的提问来源于stack exchange,提问作者Trevor
相关产品推荐
相关产品推荐

