score:0

In D3, 0 on the y coordinate is at the top rather than the bottom. You need to fist move the bars down to where you want the y axis origin to be, then move the bars up by their height to position them correctly.

Here's a rough solution though that hopefully you'll be able to work with (see the comments for the bits that have changed):

var jsonRectangles = [
  { "x_axis": 10, "y_axis": 0, "height": 65, "width":20, "color" : "green" },
  { "x_axis": 40, "y_axis": 0, "height": 80, "width":20, "color" : "purple" },
  { "x_axis": 70, "y_axis": 0, "height": 100, "width":20, "color" : "orange" },
  { "x_axis": 100, "y_axis": 0, "height": 50, "width":20, "color" : "brown" },
  { "x_axis": 130, "y_axis": 0, "height": 66, "width":20, "color" : "black" },
  { "x_axis": 160, "y_axis": 0, "height": 68, "width":20, "color" : "red" }];

// height of the visualisation - used to translate the bars
var viz_height = 100;

var svgContainer = d3.select("body").append("svg")
                                    .attr("width", 500)
                                    // set using viz_height rather than a fixed number
                                    .attr("height", viz_height);

var rectangles = svgContainer.selectAll("rect")
                             .data(jsonRectangles)
                             .enter()
                             .append("rect");

var rectangleAttributes = rectangles
                          .attr("x", function (d) { return d.x_axis; })
                          // move the bars to the bottom of the chart (using
                          // viz_height), then move them back up by the height of
                          // the bar which moves them into palce
                          .attr("y", function (d) { return viz_height - y(d.height); })
                          .attr("height", function(d) { return y(d.height); })
                          .attr("width", function (d) { return d.width; })
                          .style("fill", function(d) { return d.color; });

enter image description here

score:2

The (0,0) coordinate in an SVG is in the top left corner, so your y coordinates are "reversed" in the sense that they are counted from the top. This means that you have to position your bars so that they start at y position that you want to show and extend to the axis. Your code should look something like this.

rectangles.attr("y", function (d) { return (heightOfGraph - y(d.height)); })
          .attr("height", function(d) { return y(d.height); });

On a general note, you don't need to save rectangleAttributes in a variable -- it will be exactly the same as rectangles.


Related Query

More Query from same tag