headkit
headkit

Reputation: 3327

Why is my simple D3.js-Barchart not normalized to SVG-height correctly?

I am new to D3 and I like it a lot but with my first attempt to build a simple bar chart I am stuck at the point where I want to normalize the height of the bar charts to the full height of the SVG element. so the highest data value should scale to the full height of the SVG element. all others should scale relative. I am shure this is a stupid error but I can't see it. please help! thnx!

here is the code

  var dataset = [ 50, 43];
  var colorSet = ['rgb(143,172,206)', 'rgb(117,122,184)'];

  var w = 260;
  var h = 200;
  var barPadding = 7;



  var svg = d3.select("body")
              .append("svg")
              .attr("width", w)
              .attr("height", h);

  var x = d3.scale.ordinal()
      .domain(dataset)
      .rangeBands([0, w - (barPadding*dataset.length)]);

  var y = d3.scale.linear()
              .domain([0, 100]) //d3.max(dataset) // <- HERE SHOULD BE d3.max(dataset) CORRECT?
              .range([0,h]);

  svg.selectAll("rect")
     .data(dataset)
     .enter()
     .append("rect")
     .attr("x", function(d, i) {
        return i * (w / dataset.length);
      })
     .attr("y",  y)                             // <-- SHOULDN'T BE HERE h - y?
     .attr("width", x.rangeBand()) 
     .attr("height", y)
     .attr("fill", function(d, i) {
        return colorSet[i];
      });


svg.append("line")
  .attr("x1", 0)
  .attr("x2", w * dataset.length)
  .attr("y1", h - 0.5)
  .attr("y2", h - 0.5)
  .style("stroke", "#000");

and a link to a JSBIN

Upvotes: 0

Views: 772

Answers (1)

Matt Esch
Matt Esch

Reputation: 22966

You can't use the same y range for both the the y position and the height.

You need range([h, 0]) for the y position and range([0, h]) for the height.

To confirm this, when your data point is 100%, you want a y position of 0 and the height to be the container height. When your data is 0% you want y position to be the height of the container and the height to be 0.

Upvotes: 2

Related Questions