是否有可能找到D3.js中的刻度线之间的距离?

时间:2013-06-20 19:05:54

标签: javascript d3.js

有没有办法找出x轴上刻度线之间的距离?我使用带有rangeRoundBands的序数量表告诉我它没有tick函数。

var x= d3.scale.ordinal().rangePoints([_margin.left, cWidth]);
x.domain(['Dec','Jan']);
var testTicks = x.ticks(2);

它生成的轴很好(不能发布图像),但我无法弄清楚如何获得距离

(编辑:添加了x.domain)

2 个答案:

答案 0 :(得分:8)

var data         = [45, 31, 23], // whatever your data is
    graphHeight  = 400,
    // however many ticks you want to set
    numberTicksY = 4,
    // set y scale
    // (hardcoded domain in this example to min and max of data vals > you should use d3.max real life)
    y            = d3.scale.linear().range(graphHeight, 0]).domain(23, 45), 
    yAxis        = d3.svg.axis().scale(y).orient("left").ticks(numberTicksY),
    // eg returns -> [20, 30, 40, 50]
    tickArr      = y.ticks(numberTicksY),
    // use last 2 ticks (cld have used first 2 if wanted) with y scale fn to determine positions
    tickDistance = y(tickArr[tickArr.length - 1]) - y(tickArr[tickArr.length - 2]);

答案 1 :(得分:0)

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

ticksSpacingPow是具有所有距离的数组

下面的示例在刻度线之间的一半距离上绘制一个椭圆。

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

ps。使用最新的D3v5

const x_scale_pow = d3.scalePow().exponent(2)
    .domain([0,20000])
    .range([0, 960]);
    
const x_axis_pow = d3.axisBottom()
    .scale(x_scale_pow)
    .ticks(10)
    
// 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);

const svg = d3.select("body").append("svg")
    .attr("width", "500px")
    .attr("height","350px")
    .style("width", "100%")
    .style("height", "auto");

// 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)
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>