Published
Edited
Oct 10, 2022
Insert cell
# Pie Chart

Best uses of Pie Charts :
A+B+C+D+...=1 => Compositions,
A+B=1 => Votes, could be done with any shape
Insert cell
data = [8, 16, 2, 40, 20]
Insert cell
label = ['A','B','C','D','E']
Insert cell
pie = d3.pie()
Insert cell
pie(data)
Insert cell
pie_chart(1)
Insert cell
pie_chart = (type) => {
// Parameters
const width = 500
const OUTER = width / 3
const height = width - (width/3)
let INNER = 0
if(type==1)
INNER += OUTER / 3
const labelRadius = (INNER + OUTER) / 2
const SERVING_SIZE = 100
const color = d3.scaleOrdinal(d3.schemeCategory10)
// DOM
let svg = d3.create("svg")
.attr("height", height)
.attr("width", width)
.attr("viewBox", [-width/2, -height/2, width, height]);
let g = svg.append("g")
//// Pie code
const arc = d3.arc().innerRadius(INNER).outerRadius(OUTER)
let arcs = g.selectAll('arc')
.data(pie(data)).enter()
.append('g')
.attr('class', 'arc')
arcs.append('path')
.attr('fill', (d,i)=>color(i))
.attr('d', arc)
//// Labels
arcs.append("text")
.attr('transform', (d) => 'translate(' + arc.centroid(d) + ')')
.text((d,i) => label[i])
.attr('fill', 'white')
//// Hover
let angles_perc = calc_perc(pie(data))
if (d3.sum(angles_perc) == 100)
arcs.append("title")
.text((d,i) => angles_perc[i]+"%");
return svg.node();
}
Insert cell
function calc_perc (data) {
const angles=data.map(item => item.endAngle - item.startAngle)
const whole = d3.sum(angles)
return angles.map(item => (Math.round((item/whole)*100)).toFixed(2))
}
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