前々回はこちら
d3.jsでチャートを作る ラインチャートとバーチャートを2つのy軸上に描画する
前回はこちら
d3.jsでチャートを作る ツールチップ

SFiddleはこちら
弧上に描画するためのarc()とパイ上に配置するためのpie()を用意する。それと配色用のcolor。
1 2 3 4 5 6 7 8 9 | 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(); |
データをpie()にかませて配置用のデータへと変換する。
1 2 3 4 | var container = svg.selectAll( 'g' ) .data(pie(data)) .enter() .append( 'g' ); |
弧を描画する。
1 2 3 4 | // 色をつけて弧を描画する container.append( 'path' ) .style( "fill" , function (d, i) { return color(i); }) .attr( 'd' , arc); |
arc.centroid()を使用すると真ん中の座標が簡単に取得できる。
1 2 3 4 5 6 7 8 | // 真ん中に文字を描画する 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; }); |
弧の外側に文字を描画するには三角関数を使用して座標を算出する。またtext-anchorを角度によって変更している。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | // 外側に文字を描画する 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 - d.startAngle) / 2 + d.startAngle - Math.PI/2) , y = -labelR * Math.sin((d.endAngle - d.startAngle) / 2 + d.startAngle + Math.PI/2); return 'translate(' + x + ',' + y + ')' ; }) .attr( "text-anchor" , function (d) { var angle = (d.endAngle + d.startAngle) / 2; return 0 < angle && angle < Math.PI ? "start" : "end" ; }) .style( "fill" , function (d, i) { return color(i); }) .text( function (d, i) { return data[i].busho; }); |