我正在使用d3.js,我正在通过修改这个例子来处理拉丝区域图表.除了基于画笔的x轴变化之外,我还希望根据画笔中数据的y值重绘图表的y轴(类似于Google财经图表的行为) .
我已经使功能正常工作,但只是以能够在x和y空间中绘制画笔的方式.我通过首先在brush
变量中添加ay比例来做到这一点:
var brush = d3.svg.brush()
.x(x2)
.y(y2)
.on("brush", brush);
Run Code Online (Sandbox Code Playgroud)
这使得brush.extent()
返回以下多维数组:[ [x0, y0], [x1, y1] ]
.然后,我在brush()
函数中使用此数据重新定义焦点图的x和y域:
function brush() {
var extent = brush.extent();
x.domain(brush.empty() ? x2.domain() : [ extent[0][0], extent[1][0] ]);
y.domain(brush.empty() ? y2.domain() : [ extent[0][1], extent[1][1] ]);
focus.select("path").attr("d", area);
focus.select(".x.axis").call(xAxis);
focus.select(".y.axis").call(yAxis);
}
Run Code Online (Sandbox Code Playgroud)
这是有效的,但是通过在画笔变量中定义y比例,用户现在可以在焦点图表中拖动"框",而不是像在原始图表中那样只能向西拖动.
基本上,我的问题是:如何获得属于画笔区域的值范围,而不是画笔区域本身的范围?这甚至可能吗?
d3的笔刷文档在这里.
Sam*_*off 14
我想出了一个解决方案.
我使用刷过滤的x.domain来过滤我的原始数据集.这个新过滤的数据集只包含在画笔中的值:
// Use x.domain to filter the data, then find the max and min duration of this new set, then set y.domain to that
x.domain(brush.empty() ? x2.domain() : brush.extent());
var dataFiltered = data.filter(function(d, i) {
if ( (d.date >= x.domain()[0]) && (d.date <= x.domain()[1]) ) {
return d.duration;
}
})
y.domain([0, d3.max(dataFiltered.map(function(d) { return d.duration; }))]);
Run Code Online (Sandbox Code Playgroud)
最后,确保重绘y轴和x轴:
focus.select("path").attr("d", area);
focus.select(".x.axis").call(xAxis);
focus.select(".y.axis").call(yAxis);
Run Code Online (Sandbox Code Playgroud)