d3.js:piechart
code:d3script.css
div.bar {
display: inline-block;
width: 40px;
height: 75px;
/* background-color: teal; */
background-color: blue;
}
code:d3script.js
// データセット
const dataset = [
{ "name": "A", "value": 5 },
{ "name": "B", "value": 6 },
{ "name": "C", "value": 8 },
{ "name": "D", "value": 1 },
{ "name": "E", "value": 2 },
{ "name": "F", "value": 6 },
{ "name": "G", "value": 8 },
{ "name": "H", "value": 6 },
{ "name": "I", "value": 10 },
{ "name": "J", "value": 9 }
]
code:d3script.js
const width = 600 // グラフの幅
const height = 600 // グラフの高さ
const radius = Math.min(width, height) / 2 - 10
code:d3script.js
// SVG領域の設定
const svg = d3.select("body")
.append("svg")
.attr("width", width)
.attr("height", height)
const g = svg.append("g")
.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")")
code:d3script.js
// カラーの設定
const color = d3.scaleOrdinal()
code:d3script.js
// pieチャートデータセット用関数の設定
const pie = d3.pie()
.value((d) => d.value)
.sort(null)
code:d3script.js
// pieチャートSVG要素の設定
const pieGroup = g.selectAll(".pie")
.data(pie(dataset))
.enter()
.append("g")
.attr("class", "pie")
const arc = d3.arc()
.outerRadius(radius)
.innerRadius(radius / 2)
pieGroup.append("path")
.attr("d", arc)
.attr("fill", (d) => color(d.index) )
.attr("opacity", 0.75)
.attr("stroke", "white")
code:d3script.js
// pieチャートテキストSVG要素の設定
const text = d3.arc()
.outerRadius(radius - 30)
.innerRadius(radius - 30)
pieGroup.append("text")
.attr("fill", "black")
.attr("transform", (d) => "translate(" + text.centroid(d) + ")" )
.attr("dy", "5px")
.attr("font", "10px")
.attr("text-anchor", "middle")
.text((d) => d.data.name);
https://img.shields.io/badge/D3.js-piechart-F9A03C.svg?logo=D3.js&style=for-the-badge