Reputation: 7359
I've got a pie chart and it will only draw once. I got it from Mike Bostock's pie chart example. I'm new to D3 and I can't figure out why it won't redraw. I saw this post about redrawing a bar chart, but for some reason that technique doesn't work on my pie chart. I'm sure I'm doing something wrong.
var width = 960,
height = 500,
radius = Math.min(width, height) / 2;
var arc = d3.svg.arc()
.outerRadius(radius - 10)
.innerRadius(0);
var pie = d3.layout.pie()
.sort(null)
.value(function(d) { return d.percent; });
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");
function drawChart(error, data) {
console.log("here");
data.forEach(function(d) {
d.percent = +d.percent;
});
var g = svg.selectAll(".arc")
.data(pie(data))
.enter()
.append("g")
.attr("class", "arc");
g.append("path")
.attr("d", arc)
.style("fill", function(d) {
console.log("inside path");
return d.data.color;
});
g.append("text")
.attr("transform", function(d) { console.log("inside transform", d);return "translate(" + arc.centroid(d) + ")"; })
.attr("dy", ".35em")
.style("text-anchor", "middle")
.text(function(d) { return d.data.color; });
}
drawChart(undefined, [{"color": "green", "percent": 50}, {"color": "red", "percent": 50}]);
setTimeout(function () {
drawChart(undefined, [{"color": "green", "percent": 75}, {"color": "red", "percent": 25}]);
}, 1000)
Upvotes: 0
Views: 794
Reputation: 32327
Problem 1:
You are adding the d attribute to the DOM g which is wrong.
<g class="arc" d="M-240,2.939152317953648e-14A240,240 0 0,1 -4.408728476930471e-14,-240L0,0Z">
<path d="M-9.188564877424678e-14,240A240,240 0 1,1 1.6907553595872533e-13,-240L0,0Z" style="fill: red;">
</path>
<text transform="translate(-120,-9.188564877424678e-14)" dy=".35em" style="text-anchor: middle;">red</text>
</g>
d attribute is only for path not for g.
So this line is incorrect
g.transition().duration(750).attrTween("d", arcTween); // redraw the arcs
Problem 2:
Your update function is incorrect(same reason problem 1)
function update (data) {
console.log("here", data);
var value = this.value;
g = g.data(pie(data)); // compute the new angles
g.transition().duration(750).attrTween("d", arcTween); // redraw the arcs
};
In my opinion you should call your drawChart
function again for update.
with an exception that you remove old g group like this.
svg.selectAll(".arc").remove();
The advantage is that we are using the same code for create and update (DRY). So your timeout function becomes like thsi
setTimeout(function () {
drawChart(undefined, [{"color": "green", "percent": 75}, {"color": "red", "percent": 25}]);
}, 2000);
Full working code here
Hope this helps!
Upvotes: 2