D3.js axis label overlapping axis scale

Viewed 127

I have the following example:

Please note that this code is just a combination of code I have found online.

Is there a way to prevent the Axis label/title from overlapping the axis scale/numbers? For example here the label is overlapping the numbers. In this example I could manually hardcode the label to be positioned more to the left which would work. However, what happens when we use changing data? Say the data in the graph changes such that the y axis number may be in the 10s in one example but the next data set may have values in the 1,000,000's. Is it possible to make the graph/axis titles more dynamic/responsive to changing number lengths?

Is this something that can be done in the chart setup or is this as css issue. All suggestions or solutions are welcome.

I do not have much experience with D3.js so this may be a very simple issue to fix, I hope someone can help.

Thank you

<!DOCTYPE html>
<head>
  <meta charset="utf-8">
  <script src="https://d3js.org/d3.v5.min.js"></script>
  <style>
    body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; }
  </style>
</head>

<body>
  <script>
    var width = 400,
        height = 400;
    
    var margin = {top: 50, bottom: 50, left: 50, right: 50}

    var data = [0, 15, 20, 25, 30];
    
    // Append SVG 
    var svg = d3.select("body")
                .append("svg")
                .attr("width", width)
                .attr("height", height);
    
    // Create scale
    var scale = d3.scaleLinear()
                  .domain([ d3.max(data) , d3.min(data)])
                  .range([0, width - 100]);

    var yAxis = d3.axisLeft()
                   .scale(scale);
    
    svg.append("g")
        .attr("class", "y axis")
        .attr("transform", "translate(" + eval(margin.left-3) + ",0)")
        .call(yAxis);
        
    svg.append("text")
        .attr("class", "y label")
        .attr("text-anchor", "end")
        .attr("y", 6)
        .attr("dy", ".75em")
        .attr("transform", "rotate(-90)")
        .text("My testing title");
    
    d3.selectAll(".tick text")
            .attr("x", "-20");
    
  </script>
</body>

1 Answers

I usually go with the title coming down the right side:

    svg.append("g")
        .attr("class", "y axis")
        .attr("transform", "translate(" + eval(margin.left-3) + ",0)")
        .call(yAxis)
        .append("text")
        .text("Title")
        .attr("transform","rotate(90)")
        .attr("y",-2)
        .style('fill','black')
        .style("text-anchor","start")
Related