D3: Flip X axis

If you pull random D3 examples from the internet, you may get into a situation where chart axes are backwards from what you’d want:

E.g. this is what I had:

x.domain(d3.extent(data, (d) => d[0]));
y.domain([0, d3.max(data, (d) => d[1])]);

The easiest way to fix this is to take control over the axis endpoints, like so:

  x.domain([d3.max(data, (d) => d[0]), 0]);
  y.domain([0, d3.max(data, (d) => d[1])]);

This way you can flip them however you want, set the endpoints how you want, etc. If you just want to show data which is in your range, you can do [d3.max(…), d3.min(…)]. Alternately, if you want to make several charts that are all the same, you’d want to set them all to have the same range:

x.domain([30, 0]);

Leave a Reply

Your email address will not be published. Required fields are marked *