D3:如何通过更改数据文件源动态刷新图形?

时间:2014-09-30 19:17:54

标签: ajax d3.js graph

如何通过更改文件d3访问来按需更新数据?例如,通过单击,它将从新数据文件中读取数据,并将更多节点添加到图形中,如AJAX。

我使用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>

1 个答案:

答案 0 :(得分: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)
})