D3: How to dynamically update the chart by changing the source of the data file?

How to update data on demand by changing access to d3 files? For example, with a mouse click, he read data from a new data file and added more nodes to the chart, for example AJAX.

I use d3.tsv to read in data.tsv, one of many files of the same format.

I made a simple schedule to illustrate my question. Thanks in advance.

<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>
+4
source share
1 answer

Try it.

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)
})
+4
source

All Articles