Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/401.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 可以在D3.js中找到刻度之间的距离吗?_Javascript_D3.js - Fatal编程技术网

Javascript 可以在D3.js中找到刻度之间的距离吗?

Javascript 可以在D3.js中找到刻度之间的距离吗?,javascript,d3.js,Javascript,D3.js,有没有办法找出x轴上记号之间的距离?我使用的是带有rangeRoundBands的序数刻度,告诉我它没有刻度函数 var x= d3.scale.ordinal().rangePoints([_margin.left, cWidth]); x.domain(['Dec','Jan']); var testTicks = x.ticks(2); 它生成的轴很精细(无法发布图像),但我不知道如何获得距离 (编辑:添加了x.domain)(2019)我们可以扩展techjacker解决方案以覆盖非线

有没有办法找出x轴上记号之间的距离?我使用的是带有rangeRoundBands的序数刻度,告诉我它没有刻度函数

var x= d3.scale.ordinal().rangePoints([_margin.left, cWidth]);
x.domain(['Dec','Jan']);
var testTicks = x.ticks(2);
它生成的轴很精细(无法发布图像),但我不知道如何获得距离

(编辑:添加了x.domain)

(2019)我们可以扩展techjacker解决方案以覆盖非线性比例,而不是只计算两个刻度之间的距离,您可以拥有一个包含刻度之间所有距离的数组

// ticksDistance is constant for a specific x_scale
const getTicksDistance = (scale) => {
      const ticks = scale.ticks();
      const spaces = []
      for(let i=0; i < ticks.length - 1; i++){
        spaces.push(scale(ticks[i+1]) - scale(ticks[i]))
      }
      return spaces;
};
//you have to recalculate when x_scale or ticks change
const ticksSpacingPow = getTicksDistance(x_scale_pow);
使用最新的D3v5

常量x_scale_pow=d3.scalePow()指数(2) .domain([020000]) .范围([0960]); 常数x_axis_pow=d3.axisBottom() .scale(x_scale_pow) .滴答声(10) //对于特定的x_刻度,滴答距离是恒定的 const getTicksDistance=(比例)=>{ const ticks=scale.ticks(); 常量空间=[] for(设i=0;itickspacingpow[i]/2)
以输出范围表示的距离?只需用这两个值调用scale函数,然后减去结果。@larskothoff我正在尝试找出文字距离。例如,在一个有两个刻度的600像素宽的图表上,它们可能相距200像素。是的,因此将两个刻度值传递给刻度,然后减去返回值。您是否使用rangeRoundBands或rangePoints来构建刻度?您找到了吗?我需要找到一种方法来保持距离。
// ticksDistance is constant for a specific x_scale
const getTicksDistance = (scale) => {
      const ticks = scale.ticks();
      const spaces = []
      for(let i=0; i < ticks.length - 1; i++){
        spaces.push(scale(ticks[i+1]) - scale(ticks[i]))
      }
      return spaces;
};
//you have to recalculate when x_scale or ticks change
const ticksSpacingPow = getTicksDistance(x_scale_pow);
// normal 
svg.append("g")
    .attr("class", "x-axis")
    .attr("transform", "translate(0,20)")
    .call(x_axis_pow)
    .selectAll('.tick')
    .append('ellipse')
    .attr('fill', 'red')
    .attr('rx', '2px')
    .attr('ry', '10px')
    .attr('cx', (d,i)=> ticksSpacingPow[i]/2)