【问题标题】:D3.js axis label overlapping axis scaleD3.js轴标签重叠轴比例
【发布时间】:2022-01-03 21:17:40
【问题描述】:

我有以下例子:

请注意,此代码只是我在网上找到的代码的组合。

有没有办法防止轴标签/标题与轴刻度/数字重叠?例如,这里的标签与数字重叠。在这个例子中,我可以手动将标签硬编码到更靠左的位置,这样就可以了。但是,当我们使用不断变化的数据时会发生什么? 假设图表中的数据发生变化,因此在一个示例中 y 轴编号可能在 10 秒内,但下一个数据集的值可能在 1,000,000 秒内。是否可以使图表/轴标题更加动态/响应不断变化的数字长度?

这是可以在图表设置中完成的,还是作为 css 问题。欢迎提出所有建议或解决方案。

我对 D3.js 没有太多经验,所以这可能是一个很容易解决的问题,希望有人能提供帮助。

谢谢

<!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>

【问题讨论】:

  • 一种选择是将轴标签水平放置在轴上方,而不是在其左侧。例如:observablehq.com/@d3/line-chart
  • 在轴的右侧,垂直或水平。虽然没有确定刻度宽度的内置方法,但任何解决方案都可能基于手动计算轴刻度的边界框。
  • 谢谢你们!
  • @AndrewReid 你知道计算刻度标签长度的任何有效方法,然后确定轴标签应该移动的距离吗?

标签: javascript d3.js


【解决方案1】:

我通常把标题放在右边:

    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")

【讨论】:

    猜你喜欢
    • 2014-04-30
    • 1970-01-01
    • 2021-12-31
    • 2012-08-16
    • 1970-01-01
    • 2014-02-02
    • 2013-08-20
    • 2012-07-24
    • 2019-05-11
    相关资源
    最近更新 更多