Javascript d3简明轴更新法
我正在尝试编写一个函数来处理我的所有轴更新/输入。我现在所拥有的似乎是一个黑客,因为它需要我更新一个全局变量,以知道这是否是第一次Javascript d3简明轴更新法,javascript,d3.js,Javascript,D3.js,我正在尝试编写一个函数来处理我的所有轴更新/输入。我现在所拥有的似乎是一个黑客,因为它需要我更新一个全局变量,以知道这是否是第一次 var start = true; function axis(selection, delay) { selection.transition().duration(750).select(".x.axis") .call(xAxis) .selectAll("g") .delay(delay);
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的相同范例 您可以做一些事情,比如将一些虚拟数据绑定到您的选择。像下面这样的
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));
如果你真的想更新滴答声,你可以像迈克·博斯托克(Mike Bostock)在中所做的那样。希望这有意义 您可以检查轴的元素是否存在,而不是使用全局变量。@Larskothoff这将是一个改进的解决方案,但根据您的经验,是否有更新/进入/退出方式这样的选择选项?最后,我想使用.call方法将我的逻辑与DOM操作分离开来。我感到困惑的是,由于您没有直接将数据绑定到axis,所以我不理解更新是如何发生的。更新是由axis组件内部处理的。我不知道你说要使用enter-update-exit模式是什么意思。在我看来,你已经在这么做了。