使用d3js(v3)实现带坐标轴且基于数据驱动的简单饼图。
JS代码:
<script>
var width = 375;
var height = 375;
var padding = 25;
var padAngle = 0.01;
var moveValue = 5;
var pie = d3.layout.pie();
var color = d3.scale.category10();
var outerRadius = (width - 2 * padding) / 2;
var innerRadius = (width - 2 * padding) / 4;
window.onload = function () {
var dataset = [30, 10, 43, 55, 13];
paintPie(dataset);
};
function paintPie(data) {
d3.select("body").select("svg").data([data]).enter().append("svg")
.attr("width", width)
.attr("height", height);
var dataset = data;
var arc = d3.svg.arc()
.innerRadius(innerRadius)
.outerRadius(outerRadius);
var arcs = d3.select("svg").selectAll("g").data(pie(dataset));
arcs.exit().remove();
var arcsEnter = arcs.enter()
.append("g")
.attr("transform", "translate(" + (outerRadius + padding) + "," + (outerRadius + padding) + ")");
arcsEnter.append("path");
arcs.select("path")
.attr("fill", function (d, i) {
return color(i);
}).attr("d", function (d) {
d.padAngle = 0.01;
return arc(d);
}).on("mouseover", function (d) {
var path = d3.select(this);
var centroid = arc.centroid(d);
var tranlate = calTranslate(centroid, moveValue);
path.attr("transform", "translate(" + tranlate.x + "," + tranlate.y + ")");
}).on("mouseout", function () {
var path = d3.select(this);
path.attr("transform", "translate(0,0)");
});
arcsEnter.append("text");
arcs.select("text").attr("text-anchor", "middle")
.text(function (d) {
return d.value;
}).transition().duration(500)
.attr("transform", function (d) {
return "translate(" + arc.centroid(d) + ")";
});
}
//计算偏移(x,y)
function calTranslate(centroid, d) {
var tranlate = {};
var x = Math.sqrt(Math.pow(d, 2) / (1 + Math.pow(centroid[1], 2) / Math.pow(centroid[0], 2)));
tranlate.x = x;
if (centroid[0] < 0) {
tranlate.x = -x;
}
tranlate.y = tranlate.x * centroid[1] / centroid[0];
return tranlate;
}
function redraw() {
var dataset = [20, 10, 43, 55];
paintPie(dataset);
}
</script>
<body>
<button οnclick="redraw();">重绘</button>
</body>
效果图: