D3 - 更新条形图数据onclick [英] D3 - Update bar chart data onclick

查看:166
本文介绍了D3 - 更新条形图数据onclick的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当用户使用D3点击按钮时,我想更新我的网页内容。不幸的是,我可以看到,onclick新数据正在显示,但旧的数据不被遗忘,虽然我使用.exit()。我的更新代码如下:

I am trying to update my web page content when the user clicks on a button using D3. Unfortunately I can see that onclick new data is being displayed, but the old data is not forgotten although I use .exit(). My update code is below:

function updateData(param)
{
    // Get the data again
    d3.csv("bar-data2.csv", function(error, data) {
            data.forEach(function(d) {
            d.date = parseDate(d.date);
            d.value = +d.value;
        });
    alert(data.length);
    // Scale the range of the data again 
    x.domain(data.map(function(d) { return d.date; }));
    y.domain([0, d3.max(data, function(d) { return d.value; })]);

    // Select the section we want to apply our changes to
    var svg = d3.select("body").transition();

    d3.selectAll("bar")
    .data(data, function(d) { return(d); })
    .order()    
    .exit()
    .transition()
    //.delay(1000)
    .remove();

    // Make the changes
    svg.selectAll("bar")
      .data(data)
      .enter().append("rect")
      .style("fill", "orange")
      .attr("x", function(d) { return x(d.date); })
      .attr("width", x.rangeBand())
      .attr("y", function(d) { return y(d.value); })
      .attr("height", function(d) { return height - y(d.value); }); 
});

任何建议都将不胜感激。非常感谢!

Any suggestion would be much appreciated. Many thanks!

推荐答案

您需要选择实际存在的元素,并且只做一次:

You need to select the elements that actually exist and do that only once:

var sel = svg.selectAll("rect")
             .data(data);

sel.exit().remove();
sel.enter().append("rect")
// etc

这篇关于D3 - 更新条形图数据onclick的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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