D3.v4多系列折线图Brush缩放:contextArea设置问题求助
解决D3.v4中多系列折线图的Brush缩放问题
看起来你遇到的核心问题是D3.v3和v4的API差异,尤其是Brush和Area生成器的用法变化,我来帮你一步步修复:
1. 修复Brush的extent配置
D3.v4中brushX().extent()需要接收一个定义坐标范围的数组([[x0, y0], [x1, y1]]),而不是直接传入数据。你的代码里这里传了responses是错误的,改成:
var brush = d3.brushX() .extent([[0, 0], [width, height2]]) // 左上角到右下角的像素范围 .on("brush", brushed);
2. 修复Context Area的定义
D3.v4移除了area.interpolate()方法,改用.curve()替代;同时你代码里用了未定义的xScale2,应该用你已经声明的x2比例尺,还要给Context区域添加对应的y比例尺:
// 先添加Context的y比例尺 var y2 = d3.scaleLinear().range([height2, 0]); y2.domain(y.domain()); // 和主图y轴范围保持一致 // 修复Area生成器 var contextArea = d3.area() .curve(d3.curveMonotoneX) // 替代v3的interpolate("monotone") .x(function(d) { return x2(parseTime(d.date)); }) // 使用x2比例尺解析时间 .y0(height2) .y1(function(d) { return y2(d.temperature); }); // 用y2比例尺映射温度
3. 修复Context Area的路径绘制
你代码里responses[0].values是错误的,因为responses的结构不是包含values的对象,应该用你处理后的temp_list数据:
context.append("path") .attr("class", "area") .attr("d", contextArea(temp_list[0].values)) // 用第一个系列的数据绘制背景区域 .attr("fill", "#F1F1F2");
4. 实现核心的brushed函数
你只绑定了brush事件但没实现brushed函数,这是缩放功能的核心,用于更新主图的x轴和折线:
function brushed() { var selection = d3.event.selection; if (selection) { // 将Brush选择的像素范围转换为时间范围 var newXDomain = selection.map(x2.invert, x2); // 更新主图的x轴范围 x.domain(newXDomain); // 更新主图的所有折线 g.selectAll(".line") .attr("d", function(d) { return line(d.values); }); // 更新主图的x轴刻度 g.select(".axis--x") .call(d3.axisBottom(x)); } }
5. 修复Context的X轴绘制
D3.v4中轴的构造方式变了,你原来的call(x2)是错误的,应该用d3.axisBottom(x2):
context.append("g") .attr("class", "x axis1") .attr("transform", "translate(0," + height2 + ")") .call(d3.axisBottom(x2)); // v4的轴构造方式
其他小细节
- 确保你的
clipPath正确应用到主图的折线,避免缩放时折线超出范围:给折线添加clip-path属性:
temp.append("path") .attr("class", "line") .attr("clip-path", "url(#clip)") // 应用裁剪路径 .attr("d", function(d) { return line(d.values); }) .style("stroke", function(d) { return z(d.id); });
把这些修改替换到你代码对应的滑块部分,应该就能正常运行Brush缩放功能了。
内容的提问来源于stack exchange,提问作者Patrick Michel
相关产品推荐
相关产品推荐

