Published
Edited
May 3, 2020
1 fork
1 star
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
// D3.js 読み込み
d3 = require('d3@5')
Insert cell
Insert cell
// JSONをD3.jsが読み込める形に変換
testdataEntries = d3.entries(testdata)
Insert cell
Insert cell
pie = d3.pie().value(d => d.value)
Insert cell
Insert cell
// 円弧の開始角度と終了角度を計算
pieData = pie(testdataEntries)
Insert cell
Insert cell
// 塗りつぶし用の色スケール
colorSeq = d3
.scaleSequential()
.domain([0, Object.keys(testdata).length])
.interpolator(d => d3.hsl(d * 360, 0.5, 0.7))
Insert cell
Insert cell
{
// 描画領域
const svg = d3
.create('svg')
.attr('viewBox', [0, 0, width, height])
.attr('width', width)
.attr('height', height);
// グラフを真ん中にするためのエレメント
const chart = svg
.append('g')
.attr("transform", `translate(${radius}, ${radius})`);

// 扇型を生成する
const arc = d3
.arc()
.innerRadius(innerRadius)
.outerRadius(radius);

// 円グラフを描画する
chart
.selectAll(null) // 空のSelection
.data(pieData)
.enter()
.append('path')
.attr('d', datum => arc(datum)) // 扇型を描画する
.attr('fill', datum => colorSeq(datum.index)) // 塗りつぶし
.attr("stroke", "black")
.style("stroke-width", "1px");

// 値ラベルを描画する
chart
.selectAll(null)
.data(pieData)
.enter()
.append('text')
.text(datum => datum.data.key) // 表示するテキスト
.attr("transform", datum => `translate(${arc.centroid(datum)})`) // 扇型の中心に移動
.style("text-anchor", "middle")
.style("font-size", 20);

return svg.node();
}
Insert cell
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more