4

I'm working in D3.js and I'd like to draw an axis with tick labels offset from tick lines.

An image may be the best way to explain this:

enter image description here

So the white tick lines are not in the same place as the Jan/Feb/Mar tick labels, but are offset along the x-axis.

I am currently using an ordinal series for the x-axis, and passing in a set of explicit tickValues.

I can't see any way to offset tick lines from tick labels in the D3 axis documentation. Should I simply draw the ticks manually?

VividD
  • 10,456
  • 6
  • 64
  • 111
Richard
  • 62,943
  • 126
  • 334
  • 542

2 Answers2

5

This is indeed not directly supported, but you do have a couple of options.

  • You could have two different axes, one for the ticks and one for the labels.
  • You could hack it using the major and minor ticks. See the first answer to this question.
  • You could explicitly select the labels and offset them. See the other answer to the same question or this mailing list thread.

Depending on what you want to do, one solution may be better than the others. In particular, you need to consider whether you want all of this to update dynamically.

Community
  • 1
  • 1
Lars Kotthoff
  • 107,425
  • 16
  • 204
  • 204
0

You might want to consider using D3FC, which has a drop-in replacement for the D3 axis component that supports this feature.

With D3FC you can swap out the D3 axis for a D3FC ordinal axis as follows:

const axis = fc.axisOrdinalBottom(scale);

The D3FC ordinal axis renders labels in the center of each bar, and the ticks in between, as shown below:

enter image description here

Full disclosure - I'm a maintainer and active contributor to the D3FC project.

ColinE
  • 68,894
  • 15
  • 164
  • 232