【问题标题】:Redrawing grid lines on a line chart (remove and redraw) in d3.js在 d3.js 中重绘折线图上的网格线(删除和重绘)
【发布时间】: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


    【解决方案1】:

    我想多了,我所要做的就是添加这个:

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

    这确保之前删除了任何网格线,因此当它们被创建时,它只会以存在的那条结束。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-11-22
      • 1970-01-01
      • 2015-09-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多