如何以1秒的间隔重复执行此代码?这个想法是更新d3.js折线图并移动(平滑)图表y轴上的点。
使用随机数据添加行:
var randomNumber = Math.floor(Math.random() * 6) + 1;
data = [
[{'x':0,'y':0},{'x':5,'y':0},{'x':10,'y':0},{'x':15,'y':3},{'x':20,'y':7},{'x':25,'y': randomNumber}]
];
var path = svg.selectAll('.d3-line')
.data(data)
.enter()
.append("path")
.attr("d", line)
.attr("class", "d3-line d3-line-medium")
.style('stroke-width', 3)
.style('stroke', function(d,i){
return colors[i%colors.length];
});
添加该行的点:
// Group dots
var points = svg.selectAll('.d3-dots')
.data(data)
.enter()
.append("g")
.attr("class", "d3-dots");
// Add dots
points.selectAll('.d3-dot')
.data(function(d, index) {
var a = [];
d.forEach(function(point,i) {
a.push({'index': index, 'point': point});
});
return a;
})
.enter()
.append('circle')
.attr('class', 'd3-dot')
.attr("r", 0)
.attr("transform", function(d) {
return "translate(" + x(d.point.x) + "," + y(d.point.y) + ")"; }
)
.style("fill", "#fff")
.style("stroke-width", 0)
.style('stroke', function(d,i){
return colors[d.index%colors.length];
})
.style("cursor", "pointer");
此致
答案 0 :(得分:0)
将此添加到您的代码中以提供line chart a smooth transition
:
First add an id to the line as stated below:
var path = svg.selectAll('.d3-line')
.data(data)
.enter()
.append("path")
.attr("id", function(d,i){ return "line"+i;})
.attr("d", line)
.attr("class", "d3-line d3-line-medium")
.style('stroke-width', 3)
.style('stroke', function(d,i){
return colors[i%colors.length];
});
Following the above code add this below snippet:
d3.selectAll(".line").each(function(d,i){
// Get the length of each line in turn
var totalLength = d3.select("#line"+i).node().getTotalLength();
d3.select("#line"+i).attr("stroke-dasharray", totalLength + " " + totalLength)
.attr("stroke-dashoffset", totalLength)
.transition()
.duration(2000)
.delay(100*i)
.ease("linear") //linear, quad, bounce... other examples here - http://bl.ocks.org/hunzy/9929724
.attr("stroke-dashoffset", 0);
// .style("stroke-width",3)
});