var width = 960,
height = 500,
radius = Math.min(width, height)/2;
var color = d3.scale.ordinal()
.range(["#fdb92e", "#c02f8e", "#1aaaa9", "#ffffff"]);
var arc = d3.svg.arc()
.outerRadius(radius - 70)
.innerRadius(radius - 180);
var pie = d3.layout.pie()
.sort(null)
.value(function(d) { return d.population; });
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", "translate(" + width/2 + "," + height/2 + ")");
d3.csv("data.csv", type, function(error, data) {
if (error) throw error;
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.percentage_label); })
.style("stroke-width","0px");
g.append("text")
.attr("transform", function(d) {
return "translate(" + ((radius + 30) * Math.sin(((d.endAngle - d.startAngle)/2) + d.startAngle)) + ", " + (-1 * (radius - 10) * Math.cos(((d.endAngle - d.startAngle)/2) + d.startAngle)) +")";})
.attr("dy", ".5em")
.style("fill","#ffffff")
.style("font-size","40px")
.text(function(d) { return (d.data.percentage_label + "%"); });
g.append("circle")
.attr("transform", function(d) {return "translate(" + arc.centroid(d) + ")";})
.attr("r", 5)
.style("fill","#ffffff");
g.append("circle")
.attr("transform", function(d) {return "translate(" + ((radius - 20) * Math.sin(((d.endAngle - d.startAngle)/2) + d.startAngle)) + ", " + (-1 * (radius - 50) * Math.cos(((d.endAngle - d.startAngle)/2) + d.startAngle)) +")";})
.attr("r", 5)
.style("fill","#ffffff");
function lineCoordinates(d,x) {
/* x: coordinate to return */
//not the most efficient method
var pa = [];
var p1 = arc.centroid(d);
pa.push(p1[0]);
pa.push(p1[1]);
pa.push((radius - 20) * Math.sin(((d.endAngle - d.startAngle)/2) + d.startAngle));
pa.push(-1 * (radius - 50) * Math.cos(((d.endAngle - d.startAngle)/2) + d.startAngle));
return pa[x];
}
g.append("line")
.style("stroke","white")
.style("stroke-width","2px")
.attr("x1",function(d) { return lineCoordinates(d,0);})
.attr("y1", function(d) { return lineCoordinates(d,1);})
.attr("x2", function(d) { return lineCoordinates(d,2);})
.attr("y2", function(d) { return lineCoordinates(d,3);});
});
function type(d) {
d.population = +d.percentage_label;
return d;
}
body {
background-color: #F68135;
}
.arc text {
font: 10px sans-serif;
text-anchor: middle;
}
.arc path {
stroke: #fff;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
這是一個徹底的答案,但它並沒有幫助任何人來這裏尋找添加自定義標籤的方式與chart.js – thanksd
完全同意。解決了我的第一段。 OP問道:「如果Chart.js不可能,那麼任何人都可以指向一個圖表庫,這將允許我這樣做?」 –