JSFiddle - React, Tailwind, and code Playground
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.6/d3.min.js"></script>
<div id='item-container'></div>
CSS
.component-caption {
font: 14px sans-serif;
font-weight: bold;
}
.label.value {
font: 14px sans-serif;
font-weight: bold;
fill: white;
stroke: gainsboro;
stroke-width: 0.2px;
}
.label.name {
font: 14px sans-serif;
font-weight: bold;
}
JavaScript
var data = [
{ busho:'Branch A', sales: 96 },
{ busho:'Branch B', sales: 45 },
{ busho:'Branch C', sales: 130 },
{ busho:'Branch D', sales: 40 }
];
var width = 500
, height = 200
, radius = 150
, svg = d3.select('#item-container').append('div').append('svg')
.attr('width', width)
.attr('height', height)
.append('g')
.attr('transform', 'translate(' + width / 2 + ',' + (height) + ')');
// caption
svg.append('text')
.attr('class', 'component-caption')
.attr('text-anchor', 'middle')
.attr('transform', 'translate(0,-5)')
.text('売り上げ');
// pie
var arc = d3.svg.arc()
.innerRadius(50)
.outerRadius(radius);
var pie = d3.layout.pie()
.value(function (d) { return d.sales; })
.sort(null) // ソートはしない
.startAngle(-Math.PI / 3) // -60度から
.endAngle(Math.PI / 3); // 60度まで
var color = d3.scale.category10();
var container = svg.selectAll('g')
.data(pie(data))
.enter()
.append('g');
// 色をつけて弧を描画する
container.append('path')
.style("fill", function(d, i) { return color(i); })
.attr('d', arc);
// 真ん中に文字を描画する
container.append('text')
.attr('class', 'label value')
.attr('transform', function(d, i) {
return 'translate(' + arc.centroid(d) + ')';
})
.attr('text-anchor', 'middle')
.text(function (d, i) { return d.value; });
// 外側に文字を描画する
container.append('text')
.attr('class', 'label name')
.attr('transform', function(d, i) {
// 弧の外側を取得。パイチャートでは90度(Math.PI/2)の位置が0度計算になっているので注意。それなのでxは-する。yはSVGだと向きが逆になるので+する
var labelR = radius + 20
, x = labelR * Math.cos((d.endAngle -...