Javascript 在d3.js中重新绘制折线图上的网格线(删除并重新绘制)
我继承了一个正在使用的项目,其中一个图表是折线图;我不得不对它做了很多修改,其中之一是添加网格线,我是这样做的:Javascript 在d3.js中重新绘制折线图上的网格线(删除并重新绘制),javascript,d3.js,charts,Javascript,D3.js,Charts,我继承了一个正在使用的项目,其中一个图表是折线图;我不得不对它做了很多修改,其中之一是添加网格线,我是这样做的: grid_wrap = plot.append('g').classed('grid-wrapper', true); //...... chart = function() { //..... valueScale.domain([0, settings.value_scale_max]).range([plot_height, 0]); grid
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("")
);
//.....
}
注意上面的图表
函数在重画时被调用
function make_y_axis(valueScale) {
return d3.axisLeft()
.scale(valueScale)
.ticks(5);
}
现在,这可以很好地绘制网格线,但是,每当调整窗口大小时,它都会使用resize
事件触发器来重新绘制图形,然而,当其他所有内容都正确地重新绘制时,我的网格线会被一次又一次地重复,最后会出现几个.grid
元素
new_thresholds = thresholds.enter().append('g').attr('class', 'threshold');
thresholds.exit().remove();
我查看了其他代码是如何处理它的,我是这样理解的:
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);
图上还有这些阈值元素,它们是这样构建的:
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);
使用数据填充阈值元素
new_thresholds = thresholds.enter().append('g').attr('class', 'threshold');
thresholds.exit().remove();
现在,据我所知,thresholds
在第一次绘制时不包含任何元素,但在重画时将包含已经存在的元素
new_thresholds = thresholds.enter().append('g').attr('class', 'threshold');
thresholds.exit().remove();
new\u thresholds
随后将处理此数据并添加所需的新。threshold
元素以匹配数据集中所需的数量,因为我们在此处使用的是enter
功能
new_thresholds.append('rect').classed('threshold-rect', true).attr('x', 0).attr('y', 0).attr('width', plot_width);
向新创建的元素添加元素
new_thresholds = thresholds.enter().append('g').attr('class', 'threshold');
thresholds.exit().remove();
那么,据我所知,这将删除与我们提供的数据集相比过多的任何额外元素
//.....
}
所以我想我要问的是,既然网格线在数据集上不起作用,我如何才能实现同样的效果?我想得太多了,我所要做的就是添加以下内容:
grid_wrap.selectAll('.grid').remove();
上面是下面的代码
grid_wrap.append("g")
.attr("class", "grid")
.attr("width", grid_width)
.call(make_y_axis(valueScale)
.tickSize(-grid_width)
.tickFormat("")
);
这样可以确保在创建网格线之前删除所有网格线,因此在创建网格线时只会有一条网格线出现。我想得太多了,我所要做的就是添加以下内容:
grid_wrap.selectAll('.grid').remove();
上面是下面的代码
grid_wrap.append("g")
.attr("class", "grid")
.attr("width", grid_width)
.call(make_y_axis(valueScale)
.tickSize(-grid_width)
.tickFormat("")
);
这样可以确保在创建网格线之前删除所有网格线,因此在创建网格线时只会有一条网格线