为什么删除条形,然后将条形重新添加到我的堆栈条形图中会更改条形的位置

Why does removing, then re-adding bars to my stack bar chart change the position of the bars?

本文关键字:条形图 堆栈 我的 位置 添加 然后 删除 新添加 为什么      更新时间:2023-09-26

在我的jsfiddle中,如果您单击图例中的Pending按钮,它应该删除与该类别关联的条形图。 这有效,但是当我单击 Reset Legend 按钮(它为currateData方法提供原始数据,以便Pending条返回)时,它会加载旧的挂起数据。

我相信这与这种方法有关:

function redrawPlot() {
    svg = d3.select('svg.chart')
        .attr('width', width)
        .attr('height', height);
    svg.selectAll('g.xaxis')
        .attr('transform', 'translate(0, ' + (height - margin.top - margin.bottom) + ')');
}

我无法删除此方法,因为我的代码比 jsfiddle 中显示的代码更复杂,这只是显示问题。 我还需要更新重绘方法中的宽度和高度,所以我不能只是删除它。

如何更改 redrawPlot() 方法,以便在我重新填充图表时不会在添加旧数据时弄乱柱线位置?

问题出在redrawPlot函数上:

var svg;
function initPlot() {
    svg = d3.select('#graphTest') // <-- `svg` is the appended `g`
        .append('svg')
        // ...
        .append('g')
    // ...
}
// ...
function redrawPlot() {
    svg = d3.select('svg.chart') // <-- redefining `svg` to be `svg`
    // ...
}

问题是您正在使用全局变量svg并在 redrawPlot 中重新定义它。如果将svg的定义保留为原始定义,则图形将根据需要进行更新。通过添加var使svg的第二个定义本地化到redrawPlot解决了这个问题。

作为旁注,尽量坚持使用可重用的图表模式,避免使用全局变量。

演示

如果要重新定义svg变量

免责声明/警告:这将导致代码无法维护,不推荐。

演示 2