d3, x axis label format problem

I’m trying to label my x axis but having some trouble.

my data is as below.

const dataset = [
        { date: 2018, value: 200 },
        { date: 2019, value: 250 },
        { date: 2020, value: 180 },
        { date: 2021, value: 300 },
        { date: 2022, value: 280 },
        { date: 2023, value: 220 },
      ];

my axis setup is as below

// set up the x, scale
const x = d3.scaleLinear().range([0, width]);
const y = d3.scaleLinear().range([height, 0]);

//define x,y domain
x.domain(d3.extent(dataset, (d) => d.date));
y.domain([0, d3.max(dataset, (d) => d.value)]);

and appended the axis as below

// add x axis
      svg.append('g')
        .attr('transform', `translate(0,${height - margin.bottom})`)
        .attr('class', 'x-label-text')
        .call(d3.axisBottom(x));

and I am getting this.

I can’t seem to figure out why it’s giving me decimals, a mid point(0.5) and a comma at the thousand mark. I tried changing the data into strings but didn’t work. Tried various scales but didn’t work.

any help would great.

D3 doesn’t know that these numbers are years and creates too many tick marks. You can add .tickFormat(d3.format('0f')) to your x axis to get full numbers, and .ticks(6) in case you still get too many tick marks.

thank you for that. .ticks(6) worked like a charm.
changing the format to 0f didn’t work. it added a bunch of zeros. But .format('d) worked. not sure why though

1 Like