0
在這裏,我已經完成了餅圖。但是,當我用新數據更新內容時,它沒有正確更新。這裏錯過了什麼。點擊更新按鈕新數據正在進行。我只是選擇所需的元素和更新。更新d3.js中的餅圖沒有發生
<div>
<h2>Pie Chart</h2>
<div id="graphContainer">
</div>
<button id="update">Update</button>
</div>
$(document).ready(function() {
var width = 400;
var height = 400;
var radius = 150;
var color = d3.scale.category20c();
var data = [{
"label": "A",
"value": 20
}, {
"label": "B",
"value": 50
}, {
"label": "C",
"value": 100
}];
var circle = d3.select('#graphContainer')
.append("svg")
.data([data])
.attr("width", width)
.attr("height",height)
.append("svg:g")
.attr("transform", "translate(" + radius + "," + radius + ")");
var pie = d3.layout.pie().value(function(pieCb) {
return pieCb.value;
});
var arc = d3.svg.arc().outerRadius(radius);
var arcs = circle.selectAll("g.slice")
.data(pie)
.enter()
.append("svg:g")
.attr("class", "slice");
arcs.append("svg:path")
.attr("fill", function(d, i) {
return color(i);
}).attr("d", function(attrD) {
return arc(attrD);
});
arcs.append("svg:text").attr("transform", function(d) {
d.innerRadius = 0;
d.outerRadius = radius;
return "translate(" + arc.centroid(d) + ")";
}).
attr("text-anchor", "middle").text(function(d, i) {
return data[i].label;
});
var data1 = [{"label":"A", "value":20},
{"label":"B", "value":40},
{"label":"C", "value":30},
{"label":"D", "value":10}];
$('#update').click(function(){
/*circle.data([data1]);
arcs = circle.selectAll("g.slice")
.data(pie);
arcs.enter().append("svg:path")
.attr("fill", function(d, i) {
return color(i);
}).attr("d", function(attrD) {
return arc(attrD);
});
arcs.append("svg:text").attr("transform", function(d) {
d.innerRadius = 0;
d.outerRadius = radius;
return "translate(" + arc.centroid(d) + ")";
}).
attr("text-anchor", "middle").text(function(d, i) {
return data1[i].label;
});*/
circle.data([data1]);
var arcs = circle.selectAll("g.slice")
.data(pie)
.enter()
.append("svg:g")
.attr("class", "slice");
arcs.append("svg:path")
.attr("fill", function(d, i) {
return color(i);
}).attr("d", function(attrD) {
return arc(attrD);
});
arcs.append("svg:text").attr("transform", function(d) {
d.innerRadius = 0;
d.outerRadius = radius;
return "translate(" + arc.centroid(d) + ")";
}).
attr("text-anchor", "middle").text(function(d, i) {
return data1[i].label;
});
});
});
你見過[這個例子](http://bl.ocks.org/mbostock/5682158)? – 2014-10-31 09:23:56