我正在使用d3创建两个折线图,当用户拖动其中一个图形的范围时,这两个折线图都可以放大。我已经能够通过在拖动事件结束时重新绘制每个图形来实现它,但我想做一个更新并可能做一个动画过渡。出于某种原因,图形开始更新,但它们不会绘制新数据,因此它们只是变成空图形,即使它只是一个图形更新。我在尝试更新之前和之后都完成了console.log(newdata),并且数组中有大量数据,并且格式与原始数据相同。我确实有很多点(数千),但我已经看到d3示例可以很好地处理这些大型数据集,至少作为线图。使用Firebug,我没有错误,函数完成(rect被删除)。我意识到我还需要更新比例,但我想至少先获得数据更新。我对d3很新,所以如果我只做一些愚蠢的事情,我不会感到惊讶。任何帮助非常感谢。
以下是绘制线条的代码,后面是处理拖动事件的代码。
var line = d3.svg.line()
.x(function(d){return x_scale(d.x)})
.y(function(d){return y_scale(d.y)})
d3.select("#graph" + pointnum + " svg g")
.append("path")
.attr("d", line(data))
.attr("class", "dist_line");
var dragrect;
var dragit = d3.behavior.drag()
.on("dragstart", function(){
omsi_globals.startx = Math.round(d3.mouse(this)[0]);
dragrect = d3.select("#graph" + pointnum + " svg g")
.append("rect")
.attr("x", omsi_globals.startx)
.attr("y", 0)
.attr("width", 1)
.attr("height", omsi_globals.chart_dimensions.height)
.attr("fill", "gray")
.attr("opacity", ".1");
})
.on("drag", function(){
var currx = d3.mouse(this)[0];
if(omsi_globals.startx > currx){
dragrect.transition()
.attr("x", currx)
.attr("width", Math.abs(currx - omsi_globals.startx))
.delay(0)
.duration(10);
}
else dragrect.transition()
.attr("width", Math.abs(currx - omsi_globals.startx))
.delay(0)
.duration(10);
})
.on("dragend", function(){
var startx = omsi_globals.startx;
var endx = Math.round(d3.mouse(this)[0]);
//make sure the drag covered more than one pixel. If not, fade out the rect
if(Math.abs(startx - endx)< 1){
dragrect.transition().attr("width", 0);
return;
}
//people can drag both directions, so figure out which is lower and which is higher
var lowerx = Math.min(startx, endx);
var higherx = Math.max(startx, endx);
//we'll scale as a proportion of the current x scale (not indices, which are more regular than the data)
var currxmin = omsi_globals.d3data[pointnum-1][0].x;
var currxmax = omsi_globals.d3data[pointnum-1][omsi_globals.d3data[pointnum-1].length-1].x;
var chartwidth = omsi_globals.chart_dimensions.width;
var newmin = ((lowerx/chartwidth) * (currxmax - currxmin)) + currxmin;
var newmax = ((higherx/chartwidth) * (currxmax - currxmin)) + currxmin;
//decide if it's time to switch to raw data or not
var sourcedata = [];
var newdata = [];
//switch to raw data if down to less than threshold width
if(newmax - newmin < omsi_globals.threshold) sourcedata = omsi_globals.plotpoints[pointnum-1].raw;
else sourcedata = omsi_globals.d3data[pointnum-1];
for(i=0; i<sourcedata.length; i++){
if(sourcedata[i].x < newmax && sourcedata[i].x > newmin){
newdata.push(sourcedata[i]);
}
}
//update the global variables to be read by d3
omsi_globals.d3data[pointnum-1] = newdata;
omsi_globals.d3xranges[pointnum-1] = [newdata[0].x, newdata[newdata.length-1].x];
d3.selectAll("#graph" + pointnum + " path")
.data(newdata)
.transition()
.duration(2500)
.attr("d", line);
dragrect.remove();
});