自动刷新文字d3js

时间:2016-09-06 01:03:02

标签: javascript json d3.js

我要求使用d3js自动刷新显示的文本。 Source是一个json文件。我有以下d3js代码(基于mbostok的图表自动刷新代码)。每次都没有刷新文本。

我尝试更改json文件中的值,但发现显示的文本没有刷新。 在updateData()中,我将值打印到控制台并正确显示。不确定为什么显示的文字没有显示正确的值。

jsoncir.html

<!DOCTYPE html>
<meta charset="utf-8">
<style> /* set the CSS */

body { font: 12px Arial;}

path { 
    stroke: steelblue;
    stroke-width: 2;
    fill: none;
}

.axis path,
.axis line {
    fill: none;
    stroke: grey;
    stroke-width: 1;
    shape-rendering: crispEdges;
}

</style>
<body>

<!-- load the d3.js library -->    
<script src="http://d3js.org/d3.v3.min.js"></script>

<script>

// Set the dimensions of the canvas / graph
var margin = {top: 100, right: 20, bottom: 30, left: 50},
    width = 900 - margin.left - margin.right,
    height = 570 - margin.top - margin.bottom;


// Set the ranges
var x = d3.time.scale()
.range([0, width]);
var y = d3.scale.linear().range([height, 0]);



// Adds the svg canvas
var svg = d3.select("body")
    .append("svg")
        .attr("width", width + margin.left + margin.right)
        .attr("height", height + margin.top + margin.bottom)
    .append("g")
        .attr("transform", 
              "translate(" + margin.left + "," + margin.top + ")");

// Get the data
d3.json("final_json_file.json", function(error, data) {
    data.forEach(function(d) {

        d.close = d.cnt;


    });


  svg.selectAll("circle")
      .data(data)
      .enter().append("circle")
      .attr("class", "point")
      .attr("r", 40.5)
       .attr("fill", "#BADBDA")


      svg.selectAll("text")
      .data(data)
      .enter().append("text")
        .attr("dx", 12)
       .attr("dy", ".35em")
       .attr("text-anchor", "middle")
       .text(function(d) { return d.close })


});



var inter = setInterval(function() {
                updateData();
        }, 12000); 


        // ** Update data section (Called from the onclick)
function updateData() {

    // Get the data again
d3.json("final_json_file.json", function(error, data) {
    data.forEach(function(d) {

        d.close = d.cnt;

        console.log(d.close);

    });


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


//      console.log('ehllo');

  //    Make the changes
       svg.select("text")   // change the line
                 .duration(12000)
                .text(function(d) { return d.close +1});





    });
}


</script>
</body>

输入json文件final_json_file.json

[{“cnt”:49976,“st_time”:“2016-09-01”}]

1 个答案:

答案 0 :(得分:0)

您不会将有界数据更新为text元素。首先,您使用svg.selectAll("text").(data)将数据绑定到元素,但在updateData函数中,您没有更新数据。您应该将新数据绑定到元素,然后更新其文本。

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

//    Make the changes
svg.selectAll("text")
  .data(data)
  .transition()
  .duration(1000)
  .text(function (d) {
    return d.close + 1
  });
相关问题