自动刷新文本d3js

Auto refresh text d3js

本文关键字:d3js 文本 刷新      更新时间:2023-09-26

我需要自动刷新使用d3js显示的文本。Source是一个json文件。我有下面的d3js代码(基于mbostock的自动刷新代码图表)。文本不是每次刷新,因为它应该。

我试图改变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

[{"问":49976年,"st_time":"2016-09-01"}]

不更新有界数据到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
  });