gpt4 book ai didi

javascript - 调用两次时的 D3js 代码会复制图形而不是刷新

转载 作者:行者123 更新时间:2023-11-29 16:17:15 25 4
gpt4 key购买 nike

这是我的 D3js 代码

    function ShowGraph(data)
{

var w = 600,
h = 600,
padding = 36,
p = 31,
barwidth = 1;



var bar_height = d3.scale.linear()
.domain([d3.max(data, function(d) { return d.count; }), 0] ) // min max of count
.range([p, h-p]);

var bar_xpos = d3.scale.linear()
.domain([1580, d3.max(data, function(d) { return d.year; })] ) // min max of year
.range([p,w-p]);

var xAxis = d3.svg.axis()
.scale(bar_xpos)
.orient("bottom")
.ticks(5); //Set rough # of ticks

var yAxis = d3.svg.axis()
.scale(bar_height)
.orient("left")
.ticks(5);

var svg = d3.select("#D3line").append("svg")
.attr("width", w)
.attr("height", h);

svg.append("g")
.attr("class", "axis")
.attr("transform", "translate(0," + (h - padding) + ")")
.call(xAxis);

svg.append("g")
.attr("class", "axis")
.attr("transform", "translate(" + padding + ",0)")
.call(yAxis);

svg.selectAll("rect")
.data(data)
.enter().append("rect")
.attr("class","bar")
.attr("x", function(d) {
return bar_xpos(d.year); })
.attr("y", function(d) {
return bar_height(d.count); })
.attr("width", barwidth)
.attr("height", function(d) {return h - bar_height(d.count) - padding; })
.attr("fill", "steelblue")
}

我在点击一个按钮时运行上面的代码。当我点击按钮一次图表显示但是如果再次点击它会显示另一个图表。所以现在我得到 2 个图表。如果我再次点击我得到 3 .All i want is to update the existing graph而不是复制图表。

最佳答案

在这里你总是附加一个新的 SVG 元素(.append('svg')):

var svg = d3.select("#D3line").append("svg")
.attr("width", w)
.attr("height", h);

因此,不是使用新的 SVG 元素(因此是新图形),只需维护到第一个选定图形的链接并覆盖它或再次选择 SVG:

   var svg = d3.select( '#D3line svg' );
if ( !svg ) {

svg = d3.select("#D3line").append("svg")
.attr("width", w)
.attr("height", h);
}

或者清除 SVG 所在元素的所有内容:

document.querySelector( '#D3line' ).innerHTML = '';

关于javascript - 调用两次时的 D3js 代码会复制图形而不是刷新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13544618/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com