Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

D3: How to dynamically refresh a graph by changing the data file source?

Tags:

ajax

graph

d3.js

How do I update the data on demand by changing the file d3 accesses? With a click, for example, it would read data from a new data file and add more nodes to the graph like AJAX.

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

I made a simple graph 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>
like image 558
ngungo Avatar asked Sep 30 '14 19:09

ngungo


1 Answers

Try this.

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)
})
like image 188
Union find Avatar answered Nov 15 '22 09:11

Union find