I Like
I Like

Reputation: 1847

Why am I getting different results with same code in D3js?

I've reached an dead end in my bar chart project using d3js. I'm trying to find the sum of number of drones in different countries using data from a tsv file. Because multiple entries in the spreadsheet are from the same country I would like to add these values.

So it worked out when I ran the code once under .attr('y'). I double checked the spreadsheet and the sum added up. But when I ran the same conditional in the .attr('height') I got wonky values that messed up the bar chart. Here's the code I'm having trouble with:

 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')
        }


      });
    })

The tsv file looks like this:

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

I've put the entire code on js fiddle. I'd really appreciate help, as I've spent more than a day stressing over the solution.

Upvotes: 3

Views: 80

Answers (1)

Cyril Cherian
Cyril Cherian

Reputation: 32327

You will need to sum up your values:

So if your data is having multiple "American Samoa" then you need to sum up all the drones, which sums up to 12.

To do that make use of d3 nest to group and sum up its registration.

  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);

Now this will give you the summed up data, which can be used to make the bar chart just as this example.

working code here

Upvotes: 2

Related Questions