suMi
suMi

Reputation: 1546

d3 data scaling issue

After a while I finally figured how to scale data in d3 linear. But if you look at the following screenshot you might notice that numbers do not seem to scale appropriately: screenshot So: e.g. 4.55 and 16.2 are almost same length, which they shouldn't be (also 4 should be much closer to the left as I scale between 0 and 565)

so this is how I create the linear scale:

var scaledData = d3.scale.linear()
                      .domain(d3.extent(data, function(d){return d.Betrag;})) 
                      .range([0, width-35]);

and this is how I draw the bars:

var bar = chart.selectAll("g")
      .data(data)
    .enter().append("g")
      .attr("transform", function(d, i) { return "translate(0," + i * barHeight + ")"; });

  bar.append("rect")
    .attr("width", function(d) { return scaledData(Math.abs(Math.round(d.Betrag))); })
    .attr("height", barHeight - 1);

  bar.append("text")
    .attr("x",function(d) { return scaledData(Math.abs(Math.round(d.Betrag)))+3; })
    .attr("y", barHeight / 2)
    .attr("dy", ".35em")
    .text(function(d) { return Math.abs(d.Betrag); });
  });

I have tried around different things with this part scaledData(Math.abs(Math.round(d.Betrag))) but no matter what I do it doesn't do what I think it should... Perhaps as a newbie I still don't understand the scales thing completely... What I figure is that the problem comes from how I set the domain. if I replace the d3.extend function by [0,2000] it's all good...

Upvotes: 0

Views: 112

Answers (1)

Ethan Jewett
Ethan Jewett

Reputation: 6010

You'll have to show your data to know for sure, but I think you have negative values in your data, so your domain looks like it goes from about [-600, 1800]. But when you calculate your width you first take the absolute value of your data, so your lowest possible value is 0. The solution is in your d3.extent accessor function, to evaluate the absolute value of your data (if that's actually what you want).

Upvotes: 1

Related Questions