2014-09-30 104 views
4

如何通过更改文件d3访问来按需更新数据?例如,通过点击,它将从新的数据文件中读取数据,并为AJAX等图形添加更多节点。D3:如何通过更改数据文件源来动态刷新图形?

我使用d3.tsv来读取data.tsv,这是相同格式的许多文件之一。

我做了一个简单的图来说明我的问题。提前致谢。

<script src="http://d3js.org/d3.v3.min.js"></script> 
<script> 
    var width = 400, 
     height = 200; 

    var x = d3.scale.linear().range([0, width]), 
     y = d3.scale.linear().range([height, 0]); 

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

    d3.tsv("data.tsv", function(error, data) { 
     if (error) console.warn(error); 
     x.domain(d3.extent(data, function(q) {return q.xCoord;})); 
     y.domain(d3.extent(data, function(q) {return q.yCoord;})); 

     svg.selectAll(".dot") 
      .data(data) 
      .enter().append("circle") 
       .attr("r", 10) 
       .attr("cx", function(d) { return x(d.xCoord); }) 
       .attr("cy", function(d) { return y(d.yCoord); }) 
    }); 
</script> 
<a href="#">update the graph</a> 
+0

看看本教程:http://bost.ocks.org/mike/circles/或者在“常规更新模式”教程中。 – 2014-09-30 19:30:16

+0

我读过,但没有解决读取新数据文件的问题。 – ngungo 2014-09-30 19:50:46

+0

将更新调用中的文件路径分配给变量。在更新时更改变量路径。 – 2014-09-30 19:55:03

回答

4

试试这个。

var width = 400, 
     height = 200; 

    var x = d3.scale.linear().range([0, width]), 
     y = d3.scale.linear().range([height, 0]); 

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

var dataSource = 'data.tsv', 
dataSource2 = 'data2.tsv'; 

function updateChart(sourcefile) { 

    d3.tsv(sourcefile, function(error, data) { 
     if (error) console.warn(error); 
     x.domain(d3.extent(data, function(q) {return q.xCoord;})); 
     y.domain(d3.extent(data, function(q) {return q.yCoord;})); 

     svg.selectAll(".dot") 
      .data(data) 
      .enter().append("circle") 
       .attr("r", 10) 
       .attr("cx", function(d) { return x(d.xCoord); }) 
       .attr("cy", function(d) { return y(d.yCoord); }) 
    }); 
} 

updateChart(dataSource); 

//here is where you change the data.. 
d3.select(#button).on("click", function() { 
updateChart(dataSource2) 
}) 
+0

明白了!谢谢。 – ngungo 2014-09-30 23:16:16

+0

d3.csv只是一个函数(一个对象)。所以你可以给它更多的功能。 – 2014-09-30 23:54:26