2013-10-31 42 views
4

我有一個動態的數據源,經常在瀏覽器中創建一個新的json。更新d3與新的data.json餅圖

我能夠創建此JSON使用下面的代碼(也以this fiddle)餅圖

var data=[{"crimeType":"mip","totalCrimes":24},{"crimeType":"theft","totalCrimes":558},{"crimeType":"drugs","totalCrimes":81},{"crimeType":"arson","totalCrimes":3},{"crimeType":"assault","totalCrimes":80},{"crimeType":"burglary","totalCrimes":49},{"crimeType":"disorderlyConduct","totalCrimes":63},{"crimeType":"mischief","totalCrimes":189},{"crimeType":"dui","totalCrimes":107},{"crimeType":"resistingArrest","totalCrimes":11},{"crimeType":"sexCrimes","totalCrimes":24},{"crimeType":"other","totalCrimes":58}]; 


var width = 800, 
height = 250, 
radius = Math.min(width, height)/2; 

var color = d3.scale.ordinal() 
.range(["#98abc5", "#8a89a6", "#7b6888", "#6b486b", "#a05d56", "#d0743c", "#ff8c00"]); 

var arc = d3.svg.arc() 
.outerRadius(radius - 10) 
.innerRadius(radius - 70); 

var pie = d3.layout.pie() 
.sort(null) 
.value(function (d) { 
return d.totalCrimes; 
}); 



var svg = d3.select("body").append("svg") 
.attr("width", width) 
.attr("height", height) 
.append("g") 
.attr("transform", "translate(" + width/2 + "," + height/2 + ")"); 

var g = svg.selectAll(".arc") 
    .data(pie(data)) 
    .enter().append("g") 
    .attr("class", "arc"); 

g.append("path") 
    .attr("d", arc) 
    .style("fill", function (d) { 
    return color(d.data.crimeType); 
}); 

g.append("text") 
    .attr("transform", function (d) { 
    return "translate(" + arc.centroid(d) + ")"; 
}) 
    .attr("dy", ".35em") 
    .style("text-anchor", "middle") 
    .text(function (d) { 
    return d.data.crimeType; 
}); 

該數據更新frequenty所以這將是更新餡餅的最佳方式?看看this fiddle。在這裏我有另一個叫做data2的json。

我怎麼可以簡單地用data2替換數據,並讓餅圖動畫/更新?

注:有些更新值可以== 0

回答

17

我創建了一個工作版本,並張貼在這裏它:http://www.ninjaPixel.io/StackOverflow/doughnutTransition.html(由於某種原因,我不能讓過渡到在撥弄起球,所以剛纔它貼到我的網站,而不是)。

爲了讓代碼更加清晰,我省略了標籤,將'data'重命名爲'data1',並且卡住了一些單選按鈕以在數據數組之間翻轉。以下片段顯示了重要的部分。你可以從我的頁面上面得到整個代碼。

var svg = d3.select("#chartDiv").append("svg") 
    .attr("width", width) 
    .attr("height", height) 
    .append("g") 
    .attr("id", "pieChart") 
    .attr("transform", "translate(" + width/2 + "," + height/2 + ")"); 

var path = svg.selectAll("path") 
    .data(pie(data1)) 
    .enter() 
    .append("path"); 

    path.transition() 
     .duration(500) 
     .attr("fill", function(d, i) { return color(d.data.crimeType); }) 
     .attr("d", arc) 
     .each(function(d) { this._current = d; }); // store the initial angles 


function change(data){ 
    path.data(pie(data)); 
    path.transition().duration(750).attrTween("d", arcTween); // redraw the arcs 

} 

// Store the displayed angles in _current. 
// Then, interpolate from _current to the new angles. 
// During the transition, _current is updated in-place by d3.interpolate. 
function arcTween(a) { 
    var i = d3.interpolate(this._current, a); 
    this._current = i(0); 
    return function(t) { 
    return arc(i(t)); 
    }; 
} 

您可能會發現的麥克·博斯托克的幫助,這是我學會了如何做到這一點this代碼。