d3简洁的轴更新方法

时间:2016-02-25 15:20:40

标签: javascript d3.js

我正在尝试编写一个函数来处理我的所有轴更新/输入。我现在所拥有的似乎是一个黑客,因为它需要我更新一个全局变量来知道它是否是第一次。

var start = true;

function axis(selection, delay) {
    selection.transition().duration(750).select(".x.axis")
        .call(xAxis)
        .selectAll("g")
        .delay(delay);

    if (start) {
        start = false;
        // xaxis
        selection.append("g")
            .attr({
                "class": "x axis",
                "transform": "translate(0," + HEIGHT + ")"
            })
            .call(xAxis);

        // yaxis
        selection.append("g")
            .attr({"class": "y axis"})
            .call(yAxis)
            .append("text")
            .attr({
                "transform": "rotate(-90)",
                "y": 6,
                "dy": ".71em"
            })
            .style("text-anchor", "end")
            .text("Frequency");
     }
}

另一方面,我的条形图遵循

的模式
  • 绑定数据
  • 更新旧元素
  • 追加新元素
  • 删除旧元素

如何使用d3.axis遵循相同的范例?

1 个答案:

答案 0 :(得分:0)

你可以做一些事情,比如将一些虚拟数据绑定到你的选择。像下面这样的东西?

var xd = [0, 1]; // x domain
var yd = [0, 1]; // y domain
var y1, x1; // your axis' scales

// draw axes first so points can go over the axes
var xaxis = g.selectAll('g.xaxis')
  .data(xd);

// add axis if it doesn't exist  
xaxis.enter()
  .append('g')
    .attr('class', 'xaxis axis')
    .attr('transform', 'translate(0, ' + height + ')')
    .call(d3.svg.axis().orient("bottom").scale(x1));

// update axis if x-bounds changed
xaxis.transition()
  .duration(duration)
  .call(d3.svg.axis().orient("bottom").scale(x1));

var yaxis = g.selectAll('g.yaxis')
  .data(yd);

// add axis if it doesn't exist
yaxis.enter()
  .append('g')
    .attr('class', 'yaxis axis')
    .call(d3.svg.axis().orient("left").scale(y1));

// update axis if y-bounds changed
yaxis.transition()
  .duration(duration)
  .call(d3.svg.axis().orient("left").scale(y1));

如果你真的想要更新滴答,你可以像{Bodock在his qq example那样做。希望有意义!