2017-07-27 49 views
0

我繼承了一個使用d3.js的項目,其中一個圖表是折線圖;我不得不做出了很大的改動它,一個是增加網格線,我這樣做,像這樣:在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元素。

我檢查了其他的代碼是如何處理它,我的理解是這樣的:

還有一些圖形上的這些門檻元素和他們建立這樣:

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將不包含在第一次抽籤的任何元素,但在重繪將包含現有的元素。然後

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

然後,據我瞭解,這與我們提供的數據集相比,刪除了太多額外的元素?

//..... 

} 

所以我想我是問我如何能實現與網格線一樣的東西,因爲它不工作對數據集?

回答

0

我得太多了吧,都是我所要做的就是補充一點:

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

這可以確保任何網格之前,因此當被刪除他們被創造出來只會以那個在那裏的人結束。