只需删除的X,Y比例和轴的更新功能和使用
remove()
exit()
更新内部。
///////////////////////////// Update function
function doUpdate(gdata){
var rand = Math.floor(Math.random()*data.length)+2
var newData = data.slice(0, rand);
update(newData)
}
///////////////////////////// Create SVG
var w = 400;
var h = 250;
var margin = {
top: 20,
bottom: 40,
left: 40,
right: 20
}
var width = w - margin.left - margin.right
var height = h - margin.top - margin.bottom
var svg = d3.select(".chart-container").append("svg")
.attr("id", "svg")
.attr("width", w)
.attr("height", h)
var chart = svg.append('g')
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var x = d3.scaleBand()
.range([0, width])
.padding(0.1)
.domain(data.map(function(d) {
return d.date
}));
var y = d3.scaleLinear()
.rangeRound([height, 0])
.domain([0, d3.max(data, function(d) {
return d.value;
})]);
var xAxis = chart.append('g')
.classed('x-axis', true)
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(x))
var yAxis = chart.append('g')
.classed('y-axis', true)
.call(d3.axisLeft(y))
///////////////////////////////// Update function
function update(graphData){
console.log(graphData,graphData.length)
var u = chart.selectAll(".bar")
.remove()
.exit()
.data(graphData);
u.enter()
.append("rect")
.classed('bar', true)
.attr('x', function(d){
return x(d.date)
})
.attr("width", x.bandwidth())
.attr("y", function (d, i) {
return y(d.value);
})
.attr("height", function(d,i){
return height - y(d.value);
});
}
var button = document.getElementById('btn');
button.addEventListener('click', doUpdate);
doUpdate(data);