Search code examples
d3.jsaxisaxis-labelsyaxis

Separately controlling positioning of y-axis line and y-axis labels


I am creating a bar chart using d3. The bar chart accepts negative values. The chart I am creating is based on this chart here, and mostly have similar setup.

The change I like to make is shift the text labels of the y-axis to the absolute left of the chart, but keep the y-axis line at its original spot.

From the above link, the following are the lines of code to render the y-axis (they are at the bottom of the page, almost the last thing of the code)

svg.append("g")
  .attr("class", "y axis")
  .attr("transform", "translate(" + x(0) + ",0)")
  .call(yAxis);

Now, if I adjust the above translate line to the following

    .attr("transform", "translate(0,0)")

then BOTH the axis line AND the labels will be left aligned. I would like to keep the axis line at its position but move all the labels to the left.

How can I do that?

PS. A solution I thought about is to create second y-axis. The first y-axis is hidden with the labels shown, and is displayed to the left. The second y-axis is shown, but the labels are hidden, and is at the center. However, I do not like this solution, I do not think it is very clean.

Thanks.


Solution

  • Just increase the tick padding:

    .tickPadding(width/2 - margin.left);