d3.js The Element


<rect> represents rectangle, apart from aesthetic properties like stroke and fill, rectangle shall be defined by location and size.

As for the location, it is determined by the x and y attributes. The location is relative to the rectangle’s parent. And if you don’t specify the x or y attribute, the default will be 0 relative to the parent element.

After you specify the location, or rather the ‘starting point’ of the rect, the next thing is to specify the size, which is essential if you want to actually draw sth on the canvas, that is to say, if you don’t specify the size attributes or the value is set as 0, you won’t see anything on the canvas.

Case: Bar Chart

Continue with the first scenario, the y axes, but this time, let’s try to draw a bar chart.

Assuming the y scale setting is the same, the y axis is properly set as well, the only difference between the scatterplot and this bar chart is that, we need to specify the width and the height, particularly the height. To be more specific, we’ve already got the ‘starting point’, the rest is to use things like for the height:

.attr("height", function(d){
  return (height - yScale(d.value))