将元素附加到d3.js中的现有元素 [英] Appending an element to an existing element in d3.js

查看:114
本文介绍了将元素附加到d3.js中的现有元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图创建一个实时barchart,使用d3.js

I am trying to create a realtime barchart that plots values over time, using d3.js

这是我做的。

var dataset = [ 5, 10, 15, 20, 25 ];
var w = 1800;
var h = 500;
var barPadding = 1;

setInterval(function(){
    dataset.push(Math.floor(Math.random()*51));
    draw();
},1000);

function draw(){

    d3.select("svg").remove();
    var svg = d3.select("body")
            .append("svg")
        .attr("width", w)
        .attr("height", h);

    svg.selectAll("rect").data(dataset)
        .enter()
        .append("rect")
        .attr("x", function(d, i){return 12*i;})
        .attr("y", function(d){return h -d*4; })
        .attr("width", 11)
        .attr("height", function(d) { return d * 4; })
        .attr("fill", "teal")
        .attr("fill", function(d) { return "rgb(0, 0, " + (d * 10) + ")";});
}

问题是我每次重新绘制一个新的值添加到数据数组。

The problem is that I am redrawing the whole graph every time a new value is added to the data array.

如何在每次将新值添加到数组时向已绘制的条形图追加条形图,而不是每次重新绘制?

How do I append a bar to the bar graph that is already drawn, every time a new value is added to the array, rather than redrawing it every time?

推荐答案

您已关闭,只需停止重新绘制 svg 元素。如果你只需要添加新的元素,那么这是你的绘制函数应该做的时候调用。

You're close, just stop redrawing the svg element. If you only need to add new elements, then that's what your draw function should do when it's called.

var dataset = [ 5, 10, 15, 20, 25 ];
var w = 1800;
var h = 300;
var barPadding = 1;

var container = d3.select("body").append("svg").attr("width", w).attr("height", h).append("g");

setInterval(function(){
    dataset.push(Math.floor(Math.random()*51));
    draw();
},1000);

function draw(){

    container.selectAll("rect").data(dataset).enter().append("rect")
        .attr("x", function(d, i){return 12*i;})
        .attr("y", function(d){return h -d*4; })
        .attr("width", 11)
        .attr("height", function(d) { return d * 4; })
        .attr("fill", "teal")
        .attr("fill", function(d) { return "rgb(0, 0, " + (d * 10) + ")";});
}​

http://jsfiddle.net/Wexcode/LYqfU/

这篇关于将元素附加到d3.js中的现有元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆