我有一个垂直堆积的条形图,在rect
点击我想要更新rects,但是,它会不断添加而不是更新。这是代码:
var redrawChart = function() {
//
// Settings
//
x.domain([0, d3.max(data, function(d) { return d.total; })]);
y.domain(data.map(function(d) { return d.key; }));
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + 15 + ")")
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", ".71em")
.style("text-anchor", "end");
/////////
//ENTER//
/////////
var chartRow = svg.selectAll(".org")
.data(data);
var newRow = chartRow
.enter()
.append("g")
.attr("transform", function(d) { return "translate(0, " + y(d.key) + ")"; });
var rectRow = newRow.selectAll("rect")
.data(function(d) { return d.orgs; });
var newRect = rectRow
.enter()
.append("rect")
.attr("height", y.rangeBand())
.attr("x", function(d) { return x(d.y0); })
.attr("width", function(d) { return x(d.y1) - x(d.y0); })
.on('click', function(d){
console.log(d);
redrawChart();
})
.style("fill", function(d) { return color(d.name); });
//////////
//UPDATE//
//////////
chartRow.selectAll('rect').transition()
.duration(300)
.attr("width", function(d) { return x(d.y1) - x(d.y0); })
.attr("opacity",1);
////////
//EXIT//
////////
//Fade out and remove exit elements
rectRow.exit().transition()
.style("opacity","0")
.attr("transform", "translate(0," + (height + margin.top + margin.bottom) + ")")
.remove();
};
redrawChart();
知道我哪里错了吗?