Search code examples
d3.js

Limit chart bottom labels to 7


I'm working on a D3 line chart that requires bottom labels to be 7, but the chart has more data than 7 and want to limit it.

Here is a work-in-progress jsfiddle:

jsfiddle.net/JosephMurphy/au2y7pLs/16/

I tried setting ticks(7), but is not working

Any help getting is greatly appreciated.

Will choose best answer


Solution

  • In D3.js, the ticks() function is used to specify the approximate number of ticks to be drawn on an axis.

    If you only want to limit the number of ticks, use tickValues instead of ticks.

    const tickValues = data.map((d, i) => i % Math.round(data.length / 7) === 0 ? d.time : null).filter(Boolean);
    const xAxis = d3.axisBottom(x).tickValues(tickValues).tickFormat(d3.timeFormat('%H:%M'));
    

    https://jsfiddle.net/fw6jpe72/