Accepted answer

There are two issues with your code:

D3 parses csv/tsv/dsv entries as text. So when you load your csv, you get rows that look like this:

  "codreg": "03",
  "libreg": "Guyane",
  "year0": "2009",
  "value0": "4",
  "year1": "2014",
  "value1": "4.6"

When you set your scale with extent, you aren't using the numerical extent. You could coerce your data to a number like so:

data.forEach(function(d) {
  d.value0 = +d.value0;

Secondly, if you do this you'll notice some peculiar behavior in the placement of the bars:

enter image description here

You can see that the bars start to the left of the plot area. The reason is that you are using a linear scale, and plot the start of the bars like so:

.attr("x", function(d) {return x(Math.min(0,d.value0)); })

You want your bars to start at x(4) - which is where the x value that marks the interception with the y axis. Instead you are using x(0), which will naturally be to the left of where you want. This works in your second example, because x(0) also happens to be the x value that intercepts the y axis. Instead, you can simply use:


This marks the left edge of the plot area, which is likely where you want all your bars to be anchored to.

Here's a forked plunkr.

One thing to note, is that your shortest bar will always be non-visible: the start and end points will be the same. This is because the extent of the scale goes from the smallest value to the largest value - and the smallest value, marking the left boundary of the plot area, is the value of the shortest bar. To change this you can modify the scale's domain, perhaps using 0 as the first value and then using d3.max to find the uppermost value.

Related Query