【问题标题】:D3 Adding dots to dynamic line chartD3 在动态折线图中添加点
【发布时间】:2026-01-25 09:10:01
【问题描述】:
我有一个滚动折线图,随着数据的进入,它会实时更新。这是折线图的 js fiddle。 https://jsfiddle.net/eLu98a6L/
我想做的是用点图替换线,所以进来的每个点都会创建一个点,并保持滚动功能。这是我想创建的图表类型dow jones dot graph最终我想删除下面的线。
这是我用来尝试在图表中添加点的代码。
g.append("g")
.selectAll("dot")
.data(4)
.enter("circle")
.attr("cx", "2")
.attr("cy", "2");
到目前为止,我还没有取得任何成功。我对 d3 很陌生,因此感谢您提供任何帮助。谢谢!
【问题讨论】:
标签:
javascript
jquery
d3.js
【解决方案1】:
根据您的代码,可以采用以下方法:
var circleArea = g.append('g'); /* added this to hold all dots in a group */
function tick() {
// Push a new data point onto the back.
data.push(random());
// Redraw the line.
/* hide the line as you don't need it any more
d3.select(this)
.attr("d", line)
.attr("transform", null);
*/
circleArea.selectAll('circle').remove(); // this makes sure your out of box dots will be remove.
/* this add dots based on data */
circleArea.selectAll('circle')
.data(data)
.enter()
.append('circle')
.attr('r',3) // radius of dots
.attr('fill','black') // color of dots
.attr('transform',function(d,i){ return 'translate('+x(i)+','+y(d)+')';});
/* here we can animate dots to translate to left for 500ms */
circleArea.selectAll('circle').transition().duration(500)
.ease(d3.easeLinear)
.attr('transform',function(d,i){
if(x(i )<=0) { // this makes sure dots are remove on x=0
d3.select(this).remove();
}
return 'translate('+x(i-1)+','+y(d)+')';
});
/* here is rest of your code */
// Slide it to the left.
d3.active(this)
.attr("transform", "translate(" + x(-1) + ",0)")
.transition()
.on("start", tick);
// Pop the old data point off the front.
data.shift();
}
查看实际操作:https://codepen.io/FaridNaderi/pen/weERBj
希望对你有帮助:)