2014-09-30 2 views
4

d3 액세스를 변경하여 요청시 데이터를 어떻게 업데이트합니까? 예를 들어, 클릭하면 새 데이터 파일에서 데이터를 읽고 AJAX와 같은 그래프에 노드를 추가합니다.D3 : 데이터 파일 원본을 변경하여 그래프를 동적으로 새로 고치는 방법은 무엇입니까?

같은 형식의 여러 파일 중 하나 인 data.tsv를 읽으려면 d3.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/ 또는 "일반 업데이트 패턴"자습서를 살펴보십시오. –

+0

나는 그것을 읽었지만 새로운 데이터 파일을 읽는 문제를 다루지는 않는다. – ngungo

+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) 
}) 
+0

알았습니다! 감사. – ngungo

+0

d3.csv는 하나의 함수 (객체)입니다. 따라서 더 많은 기능을 제공 할 수 있습니다. –

관련 문제