Contents

How to Manage x Axis in D3.js?

Contents
You want to know how to display x axis in D3.js? In this article, I will show you how to do it properly using the axisBottom function.

D3 allows us to simply link axis with scales.

First we need to define an svg canvas as usual, let’s do it.

1
2
3
4
const svg = d3.select(#canvas).append("svg").attr("width", 400).attr("height", 500)

const g = svg.append("g")
  .attr("transform", `translate(100, 10)`)

As you can see, we added a g object to allow us to display several values on the x axis. The attribute “transform” applies a function to all objects linked to g. Here we just translate objects with 100 pixels on the x axis and 10 pixels on the y axis.

Now let’s add a simple band scale.

1
2
3
4
5
const x = d3.scaleBand()
    .domain(["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"])
    .range([0, 290])
    .paddingInner(0.3)
    .paddingOuter(0.2)

The basic type of scales in D3.js are explained in articles available on datackling.com/blog.

Let’s use the axisBottom function now.

const xAxis = d3.axisBottom(x)

1
2
3
4
5
6
7
8
9
g.append("g")
    .attr("class", "x axis")
    .attr("transform", `translate(0, 360)`)
    .call(xAxisCall)
    .selectAll("text")
      .attr("y", "10")
      .attr("x", "-5")
      .attr("text-anchor", "end")
      .attr("transform", "rotate(-40)")

That’s it! The magic of D3 operate in the axisBottom function. We pass in argument the reference of the band scale define above. D3 will automatically use the input domain to get the values to display on the x axis and the length of the x axis.

We use the g object to add texts on x axis that corresponds to the input domain of the scale band (here we chose day of the week).

I hope you enjoyed this article. If you get stuck, do not hesitate to ask your questions in DM.

See you!