0
我想創建一個使用JSON文件來存儲數據的動畫餅圖。d3js動畫餅圖使用JSON
我的JSON文件是這樣的:
{"data":[
{"ap": [
{"floorratio": [
{"floor":"Basement", "ratio": 0.20},
{"floor":"Ground", "ratio": 0.20},
{"floor":"First Floor", "ratio": 0.15},
{"floor":"Second Floor", "ratio": 0.20},
{"floor":"Third Floor", "ratio": 0.25}
]}
]},
{"ap": [
{"floorratio": [
{"floor":"Basement", "ratio": 0.10},
{"floor":"Ground", "ratio": 0.30},
{"floor":"First Floor", "ratio": 0.10},
{"floor":"Second Floor", "ratio": 0.15},
{"floor":"Third Floor", "ratio": 0.35}
]}
]}
]}
和我的HTML代碼:
<!doctype html>
<html>
<head>
<title>Pie Chart Test</title>
<script src="d3.min.js"></script>
</head>
<style>
body {
font: 10px sans-serif;
}
.arc path {
stroke: #fff;
}
</style>
<body>
<label><input type="radio" name="dataset" value="0" checked> 1</label>
<label><input type="radio" name="dataset" value="1"> 2</label>
<script>
var width = 960,
height = 500,
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(0);
var pie = d3.layout.pie()
.sort(null)
.value(function (d) { return d.ratio;});
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", "translate(" + width/2 + "," + height/2 + ")");
var nodeSelected;
d3.json("APCategories.json", function (error, data) {
//initialise data
floorRatio = data.data[0].ap[0].floorratio;
var g = svg.selectAll(".arc")
.data(pie(floorRatio))
.enter().append("g")
.attr("class", "arc");
g.append("path")
.attr("d", arc)
.style("fill", function (d) {
return color(d.data.floor);
})
.each(function(d) {this._current = d;});
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.floor;
});
//showing initial pie chart code ends here
function changePieChart() {
nodeSelected = this.value;
newFloorRatio = data.data[nodeSelected].ap[0].floorratio;
g = g.data(pie(newFloorRatio));
g.transition().duration(750).attrTween("d", arcTween);
}
function radioSelectedChange() {
nodeSelected = this.value;
changePieChart();
}
d3.selectAll("input")
.on("change", changePieChart);
function arcTween(a) {
var i = d3.interpolate(this._current, a);
this._current = i(0);
return function(t) {
return arc(i(t));
};
}
});
</script>
</body>
</html>
所以此刻我只裝了第一組數據,因爲我打電話
floorRatio = data.data[0].ap[0].floorratio
但我想要能做的是有更多的東西沿線:
floorRatio = data.data[i].ap[0].floorratio
我試圖做到這一點在changePieChart功能,但是我認爲問題出在數據正開始,我不太清楚正確的方式使用JSON文件來做到這一點。
注:我的json文件只是一個更大版本的小例子。
我想創建一個更新/更改的餅圖,但我不確定如何使用JSON數據。 加載所有數據然後使用它的正確方法是什麼?
使用它,我將如何去顯示第一個數據集? –
看看這個鏈接 - 它會爲對象數量創建多個svg元素並繪製數據。 http://plnkr.co/edit/GrR6xzvZDmUCjRX3m2fv?p=preview。如果它解決了您的問題,請接受答案。 – somename
第一個鏈接沒有顯示任何內容,但我現在看到。我試圖製作一個動畫餅圖(一個餅圖更改/更新) –