Get ticks on x-axis with scalesBand centered below columns with d3 v6

Viewed 121

Edit: Problem solved

The bitter insight: I have done the translate wrong: the axis is wrongly moved to the right. Solution .attr('transform', translate(0,${input.height - margins.current.bottom}))

Original Post

I do not understand how to get the positions of the ticks of my x-axis right. The ticks should be centered right below the columns.

With d3 I am creating a band scale for the right width of the columns and I would like to reuse it for the x-axis.

Code

// data
data [
  {
    "year": "2021",
    "value": 7.81335178927304
  },
  {
    "year": "2022",
    "value": 7.103485903424945
  },
  {
    "year": "2023",
    "value": 6.393620017576849
  }
  // [...]
]

// original band scale
const xScale = scaleBand()
    .domain(yearsData.map((d) :string => d.year))
    .rangeRound([0, (input.width - margins.current.left - margins.current.right)])
    .padding(0.1);

// creating the x-axis
const xAxis = axisBottom(xScale.copy().padding(0.5).align(0));
const xAxisGroup = chartGroup.append('g')
    .attr('class', 'x-axis')
    .call(xAxis)
    // move the whole axis down, variables do not matter here
    .attr('transform', `translate(${margins.current.left},${input.height - margins.current.bottom})`)

Result

Weird position of ticks:

Do I need to use timeScale here?

Different ways of setting paddings on the copied band scale produces different results, but no centered ticks. Also I am wondering about the very first tick on the left, why is it there? Trying point scale did not work, too.

0 Answers
Related