简体   繁体   中英

d3.js ticks for axis displayed wrong

I have a problem regarding ticks for the axis label using d3.js

This is my code:

const svg = d3.select('svg').attr('width', 1000).attr('height', 600);
const layer = svg.append('g').attr('transform', `translate(30, 30)`);
const scale = d3.scaleLinear().range([0, 750]).domain([0, 350]);
const axis = d3.axisTop(scale).ticks(14);
layer.call(axis);

So what i want to do is, have 14 labels regarding the data. So by dividing 350/14 a step should be of size 25.

If you take a look at the result, the ticks are rounded somehow to 20, which I do not know why.

Does anyone know what d3 is doing here? What am I doing wrong?

Thanks in advance!

Output

The number of ticks you pass is only a hint to d3. According to the observable documentation here :

For linear and power scales, pass axis.ticks the desired tick count. This is just a hint: these scales only generate ticks at 1-, 2-, and 5-multiples of powers of ten, so the actual number of ticks may be different.

If you want to use labels on the axis, you should consider using the scaleBand which is demonstrated here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM