Reputation: 2807
I have a stacked bar chart. The jsfiddle is here.
I have added a text which is actually the sum of all stacks on top of each bar.
layer.selectAll("rect")
.data(data)
.enter().append("text")
.attr("text-anchor", "middle")
.attr("x", function (d) { return x(d[chartType]) + x.rangeBand() / 2; })
.attr("y", function(d)
{
return y(sumOfStack(chartType, data, d[chartType], xData)) - 5;
})
.text(function(d)
{
return sumOfStack(chartType, data, d[chartType], xData);
})
.style("fill", "4682b4");
And the sumOfStack() method returns the value of y actually. It sums up all the stack values.
function sumOfStack(dataType, data, xValue, sources)
{
var sum = 0;
for(var i=0; i<data.length;i++){
if(data[i][dataType] != xValue) continue;
for(var j=0; j<sources.length; j++)
{
sum+= data[i][sources[j]];
}
console.log(sum);
return sum;
}
}
So what is happening here, first time, the monthly chart is drawn and the value on the top is correct. But, when I click on the quarter/year, the values are not recalculating.
What's the problem here?
Upvotes: 0
Views: 110
Reputation: 737
You are only using the append part of the selection, which takes care of new elements, while the texts that you need to update already exists, so they don't belong to the enter() part but to the existing selection.
Replace the totals with this code and it should work:
var totals = svg.selectAll('text.totalLabels')
.data(data);
totals
.transition()
.duration(500)
.attr("x", function (d) { return x(d[chartType]) + x.rangeBand() / 2; })
.attr("y", function(d)
{
return y(sumOfStack(chartType, data, d[chartType], xData)) - 5;
})
.text(function(d)
{
return sumOfStack(chartType, data, d[chartType], xData);
});
totals.enter().append('text')
.attr('class', 'totalLabels')
.attr("text-anchor", "middle")
.attr("x", function (d) { return x(d[chartType]) + x.rangeBand() / 2; })
.attr("y", function(d)
{
return y(sumOfStack(chartType, data, d[chartType], xData)) - 5;
})
.text(function(d)
{
return sumOfStack(chartType, data, d[chartType], xData);
})
.style("fill", "4682b4");
totals.exit().remove();
Upvotes: 1