2016-12-17 3 views
3

d3js를 사용하여 막 대형 차트 프로젝트에서 막 다른 골목에 도달했습니다. tsv 파일의 데이터를 사용하여 다른 국가의 무인 항공기 수를 찾으려고합니다. 스프레드 시트의 여러 항목이 같은 국가 출신이므로 이러한 값을 추가하고 싶습니다.D3js에서 같은 코드로 다른 결과가 나타나는 이유는 무엇입니까?

코드를 .attr('y')에서 한 번 실행했을 때 효과가있었습니다. 나는 스프레드 시트를 두 번 확인하고 합계를 더했다. 그러나 .attr('height')에서 동일한 조건부를 실행했을 때 막 대형 차트를 엉망으로 만들었습니다. 저는 여기에 문제가있어 코드는 다음과 같습니다

g.selectAll(".bar") 
    .data(data) 
    .enter().append("rect") 
     .attr("class", "bar") 
     .attr("x", function(d) { return x(d.Country); }) 
     .attr("y", function(d,i) { 

     try{ 
      if (data[i].Country == data[i-1].Country){ 

      data[i].Registration += data[i-1].Registration; 
      } 
      else{ 
      console.log(data[i-1].Country + ' ' + data[i-1].Registration); 
      return data[i-1].Registration;//y(data[i-1].Registration); 
      } 
     } 
     catch(err){ 
      console.log('did not work') 
     } 

     }) 
     .attr("width",20) 
     .attr("height", function(d,i) { 
     try{ //SAME CODE DIFFERENT REGISTRATION VALUES 

      if (data[i].Country == data[i-1].Country){ 
      data[i].Registration += data[i-1].Registration; 
      } 
     else{ console.log(data[i-1].Country + ' ' + data[i-1].Registration); return (height - data[i-1].Registration);} 
     } 
     catch(err){ 
      console.log('did not work') 
     } 


     }); 
    }) 

TSV를 파일은 다음과 같다 :

Country Registration 
land Islands 1 
American Samoa 1 
American Samoa 1 
American Samoa 1 
American Samoa 6 
American Samoa 1 
American Samoa 1 
American Samoa 1 
Antigua and Barbuda 1 
Argentina 1 
Australia 1 
Australia 2 
Australia 1 
Australia 1 
Brazil 1 
Brazil 1 
Brazil 1 

내가 JS 바이올린에 entire code을 넣었습니다. 나는 해결책을 강조하는 하루 이상을 보냈으므로 도움을 정말 감사 할 것입니다.

+0

정확히 무엇을 원하는지 말할 수 있습니까? –

+0

JSFiddle이 작동하지 않습니다. 그것은 D3가 없기 때문에 다른 오류가 있다고 수정 한 후에도 마찬가지입니다. – altocumulus

+1

다른 결과가 나타나는 이유는'data [i] .Registration + = data [i-1]. 등록;을 할 때 실제로 데이터를 변경하기 때문입니다. [추가 대입 연산자] (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Assignment_Operators#Addition_assignment)'+ ='에 주목하십시오. 'height' 콜백에서 계산을 할 때, 여러분의 데이터는 이미'y'에 대한 이전 콜백에 의해 변경되었습니다. 가능한 솔루션은 Cyril의 [answer] (http://stackoverflow.com/a/41197222/4235784)에서 제공됩니다. – altocumulus

답변

2

당신은 당신의 가치를 요약해야합니다

그래서 당신의 데이터는 당신이해야 할 12

에 요약 모든 드론을 요약 할 필요가있는 복수 "아메리칸 사모아"가 있는지 d3 nest을 사용하여 등록을 그룹화하고 요약합니다.

var data_sum = d3.nest() 
    .key(function(d) { return d.Country; })//group by country 
    .rollup(function(v) { return d3.sum(v, function(d) { return d.Registration; }); })//roll up all resgistrations 
    .entries(data); 

지금이 당신에게 그냥이 example로 막대 차트를 만드는 데 사용할 수있는 요약 데이터를 제공 할 것입니다.

작업 코드 here

+1

나는 왜 이것이 일어나고 있는지 설명하는 [comment] (http://stackoverflow.com/questions/41196660/why-am-i-getting-different-results-with-same-code-in-d3js#comment69596046_41196660)을 추가했습니다. 대답에도이 내용을 포함 시키십시오. – altocumulus

관련 문제