简体   繁体   English

d3js:为tickPadding提供函数

[英]d3js: supply a function to tickPadding

Say I have a graph where the x-axis tick labels are very long strings , and so I want to alternate the tick padding (the vertical distance between the text and the x-axis) so that the tick labels don't overlap. 假设我有一个图,其中x轴刻度标签是很长的字符串 ,所以我想交替使用刻度线填充(文本和x轴之间的垂直距离),以使刻度标签不重叠。

I know this can be achieved post-rendering by selecting the tick elements and applying a transform attribute. 我知道可以通过选择tick元素并应用transform属性来实现后期渲染。 But I'd like to do: 但我想这样做:

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;
 });

This doesn't work in d3 as-is -- the documentation ( https://github.com/mbostock/d3/wiki/SVG-Axes#wiki-tickPadding ) says that tickPadding just takes the number of pixels. 这在d3中不起作用-文档( https://github.com/mbostock/d3/wiki/SVG-Axes#wiki-tickPadding )说tickPadding只需要像素数。 Is there a better way to do this? 有一个更好的方法吗? Monkey patch d3's axis.tickPadding function to take a function or a number, then apply the function when drawing the ticks? 猴子补丁d3的axis.tickPadding函数接受一个函数或一个数字,然后在绘制刻度时应用该函数?

I also was hoping to do this. 我也希望这样做。 I was using week numbers and it got a little cramped. 我用的是周数,所以有点局促。 Basically the x axis looked like 基本上x轴看起来像

111213141516171819 

and I was hoping to stack them. 我希望将它们堆叠起来。 I ended up doing this 我最终这样做了

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

Once the graph was drawn. 一旦绘制图形。 I made sure to include some extra margin (10) on the bottom as well. 我确保在底部也包括一些额外的边距(10)。 The result was 结果是

  12  14  16  18
11  13  15  17  19

The only choice you have is to modify the source. 您唯一的选择是修改源。 D3 assumes throughout the axis implementation that tickPadding is a number, not a function -- see the source . D3在整个轴实现中tickPadding假定tickPadding是一个数字,而不是一个函数-参见源代码

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM