简体   繁体   中英

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: 屏幕截图 So: eg 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...

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM