Last active April 11, 2013

Embed URL

HTTPS clone URL

SSH clone URL

Say your dataset is an array of numbers, and includes both positive and negative values. Use two scales to construct the bar chart: a quantitative scale (such as a linear scale) to compute the bar positions along the x-axis, and an ordinal scale with rangeBands to compute the bar positions along the y-axis.

For the quantitative scale, compute the data domain (the minimum and maximum value) using d3.extent:

Nicing the scale will extend the extent slightly to the nearest round numbers. If you want the zero-value to be centered in the middle of the canvas, take the greater of the minimum and maximum value by magnitude, or simply hard-code the desired domain.

For the y-axis, use rangeRoundBands to divide the vertical space into bands for each bar and specify the amount of padding between bars. The input (domain) to the ordinal scale is some identifying data—such as a name or a unique id. A simple such identifier is the data’s index:

Use both scales to position the bars. This is made slightly tricky in that SVG rects are positioned (the x and y attributes) by their top-left corner and cannot have a negative width or height. So, we must use the x- and y-scales to compute the position of the top-left corner, depending on whether the associated value is positive or negative: if the value is positive, then the data value determines the right edge of the bar, while if it’s negative, it determines the left edge of the bar. Hence the conditionals: