【发布时间】:2018-01-03 13:59:34
【问题描述】:
我继承了一个使用d3.js 的项目,其中一个图表是折线图;我必须对其进行很多更改,其中一个是添加网格线,我是这样做的:
grid_wrap = plot.append('g').classed('grid-wrapper', true);
//......
chart = function() {
//.....
valueScale.domain([0, settings.value_scale_max]).range([plot_height, 0]);
grid_wrap.append("g")
.attr("class", "grid")
.attr("width", grid_width)
.call(make_y_axis(valueScale)
.tickSize(-grid_width)
.tickFormat("")
);
//.....
}
注意上面的 chart 函数在重绘时被调用。
function make_y_axis(valueScale) {
return d3.axisLeft()
.scale(valueScale)
.ticks(5);
}
现在,这可以很好地绘制网格线,但是每当调整窗口大小时,它都会使用resize 事件触发器来重绘图形,但是当其他所有内容都正确重绘时,我的网格线会一遍又一遍地重复,最终会出现几个.grid 元素。
我检查了其他代码是如何处理它的,我是这样理解的:
图上还有这些 threshold 元素,它们是这样构建的:
thresholds = plot.append('g').classed('thresholds', true);
chart = function() {
//.....
valueScale.domain([0, settings.value_scale_max]).range([plot_height, 0]);
thresholds = plot.select('.thresholds').selectAll('.threshold').data(chart.Thresholds);
使用数据填充 threshold 元素。
new_thresholds = thresholds.enter().append('g').attr('class', 'threshold');
现在,据我了解,thresholds 在第一次绘制时不会包含任何元素,但在重绘时将包含已经存在的元素。
new_thresholds 然后将处理此数据并添加所需的新 .threshold 元素以匹配数据集中所需的数量,因为我们在这里使用enter 函数。
new_thresholds.append('rect').classed('threshold-rect', true).attr('x', 0).attr('y', 0).attr('width', plot_width);
向我们新创建的元素添加元素。
thresholds.exit().remove();
那么据我了解,这会删除与我们提供的数据集相比过多的任何额外元素?
//.....
}
所以我想我要问的是如何使用网格线实现相同的效果,因为它不适用于数据集?
【问题讨论】:
标签: javascript d3.js charts