y轴和y轴标签d3js之间的空间

时间:2019-11-20 13:14:07

标签: javascript d3.js data-visualization

使用助手创建y轴,但似乎无法在该轴和标签之间创建更多空间。我尝试使用eval(margin.left-3)进行移动,但这也使轴移动。有什么想法吗?

svg.append("g")
        .attr("class", "y axis")
        .attr("transform", "translate(" + eval(margin.left-3) + ",0)")
        .call(yAxis);

1 个答案:

答案 0 :(得分:0)

您需要专门选择刻度线中的文本,然后更改其属性以使其移动:

d3.selectAll(".tick text") // selects the text within all groups of ticks
        .attr("x", "-20"); // moves the text to the left by 20

完整的代码段:

<!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);
    
    d3.selectAll(".tick text")
     		.attr("x", "-20");
    
  </script>
</body>