【问题标题】:d3js: supply a function to tickPaddingd3js:为 tickPadding 提供一个函数
【发布时间】:2013-11-19 22:02:54
【问题描述】:

假设我有a graph where the x-axis tick labels are very long strings,所以我想改变刻度填充(文本和 x 轴之间的垂直距离),这样刻度标签就不会重叠。

我知道这可以通过选择刻度元素并应用转换属性来实现后渲染。但我想做:

var xAxis = d3.svg.axis()
.scale(x0)
.orient("bottom")
.tickSize(0)
.tickPadding(function(i) {
  // some logic here to determine the alternating-height strategy by index, e.g.
  return i % 2 ? 20 : 30;
 });

这在 d3 中不起作用——文档 (https://github.com/mbostock/d3/wiki/SVG-Axes#wiki-tickPadding) 说 tickPadding 只需要像素数。有一个更好的方法吗? Monkey patch d3的axis.tickPadding函数取一个函数或者一个数字,然后在绘制tick的时候应用这个函数?

【问题讨论】:

    标签: javascript svg d3.js


    【解决方案1】:
    【解决方案2】:

    我也希望这样做。我使用的是周数,它有点局促。基本上x轴看起来像

    111213141516171819 
    

    我希望将它们堆叠起来。我最终这样做了

    $('.tick text').each(function(i){
       var yval = this.getAttribute("y");
       if( i % 2 == 0 )this.setAttribute("y",parseInt(yval)+10);
    });
    

    图表绘制完成后。我确保在底部也包含一些额外的边距(10)。结果是

      12  14  16  18
    11  13  15  17  19
    

    【讨论】:

    • 谢谢。我们通过 d3 selection 而不是 JQ 做了类似的事情: xAxis.selectAll('text') .attr('transform', function (d,i) { var y = i % 2 === 0 ? 10 : 0; //将偶数向下移动 return 'translate(0,' + y + ')'; });
    【解决方案3】:

    您唯一的选择是修改源。 D3 在整个轴实现中假定tickPadding 是一个数字,而不是一个函数——参见the source

    【讨论】:

      猜你喜欢
      • 2021-08-02
      • 2020-10-07
      • 2023-03-12
      • 2015-05-25
      • 2018-05-15
      • 2018-06-07
      • 2019-06-20
      • 2020-06-11
      • 1970-01-01
      相关资源
      最近更新 更多