javascriptd3.js

unable to adjust d3 y-axis label position


I want to vertically center the y-axis label on a d3 graph. Right now, I have the label at the top of the y-axis. When I try to adjust the y or dy attributes, the label moves horizontally, not vertically. I suspect this has to do with the label being rotated, but when I comment out the rotation, the label disappears.

<div id="container"></div>
<script type="module">

const width = 1140;
const height = 400;
const marginTop = 20;
const marginRight = 20;
const marginBottom = 50;
const marginLeft = 70;

const x = d3.scaleUtc()
    .domain([new Date("2007-01-01"), new Date("2023-01-01")])
    .range([marginLeft, width - marginRight]);

const y = d3.scaleLinear()
    .domain([0, .5])
    .range([height - marginBottom, marginTop]);

const svg = d3.create("svg")
    .attr("width", width)
    .attr("height", height);

svg.append("g")
    .attr("transform", `translate(0,${height - marginBottom})`)
    .call(d3.axisBottom(x)
        .ticks(d3.utcYear.every(1))
);
    
svg.append("text")
    .attr("class", "x label")
    .attr("text-anchor", "end")
    .attr("x", width/2)
    .attr("y", height - 6)
    .text("Year");

svg.append("text")
    .attr("class", "y label")
    .attr("text-anchor", "end")
    .attr("y", 6) //if I change this value, the label moves horizontally
    .attr("dy", ".75em") //if I change this value, the label moves horizontally
    .attr("transform", "rotate(-90)") //if I comment this out, the label disappears
    .text("Percent");

svg.append("g")
    .attr("transform", `translate(${marginLeft},0)`)
    .call(d3.axisLeft(y));

container.append(svg.node());

Solution

  • I believe because you rotate the y-axis label by -90 you need to apply the attr to x so that it moves "left and right" but that would be rotated by 90 so it would move up and down. If that makes sense.