d3 axes: help me understand the very basics

So I’m trying to use d3’s axis generator by reading these docs.
The docs make clear how to render an axis for a given scale. For instance:

svg.append("g")
    .attr("transform", `translate(0,${height - marginBottom})`)
    .call(d3.axisBottom(x));

But then the question arises as to how to customize the tic marks.

According to the docs, if I’ve somehow gotten ahold of an axis object in my code, then I can do things to that object like this:

axis.ticks(20, "s");

So, naturally, I’m now looking to figure out how to get my hands on that object. As best I can tell (sorry if I’m missing something), I can get an axis returned from d3.axisBottom like this:

const xAxis = d3.axisBottom().scale(x);

But if I do that AFTER I do…

svg.append("g")
    .attr("transform", `translate(0,${height - marginBottom})`)
    .call(d3.axisBottom(x));

…Am I going to get a reference to that same axis that I just rendered? Or instead do I need to be using some other method of rendering the axis if I also want control over the ticks?

Probably, my problem is that I don’t know what call() does?

Wish the docs included an example showing both the rendering of an axis AND the specification of ticks.

Help?

When you call d3.axisBottom(x), you are making a new, independent “axis maker” each time.So what you want to do is make an axis maker, customize it, and then pass it to .call(). Like this:

const xAxis = d3.axisBottom(x) // this makes a new axis-maker
  .tick(20, "s"); // this customizes it, and then returns the axis-maker

svg.append("g")
    .attr("transform", `translate(0,${height - marginBottom})`)
    .call(xAxis); // here I use the axis-maker I made and customized above

What .call() does is call the given function with the selection you have (here, the g element you just made). That means that the return value of d3.axisBottom is actually a kind of function. It is just one that has been given extra properties and methods.

1 Like