Published
Edited
Aug 23, 2020
Fork of Pie Chart
Importers
Insert cell
md`# Pie Chart`
Insert cell
d3 = require("d3@5")
Insert cell
import { formatNumber, formatPercent } from '@nuuuwan/string-utils'
Insert cell
P_LIMIT = 0.05
Insert cell
function drawPieChart(dataOriginal) {
const totalValue = dataOriginal.reduce(function(totalValue, datum) {
totalValue += datum.value;
return totalValue;
}, 0);

let data = dataOriginal.filter(datum => datum.value >= totalValue * P_LIMIT);
const totalValueFiltered = data.reduce(function(totalValue, datum) {
totalValue += datum.value;
return totalValue;
}, 0);

if (totalValue > totalValueFiltered) {
data.push(
Object({
name: 'Others',
value: totalValue - totalValueFiltered
})
);
}

const [width, height] = [500, 500];

const pie = d3
.pie()
.sort(null)
.value(d => d.value);

const arcs = pie(data);

const color = d3
.scaleOrdinal()
.domain(data.map(d => d.name))
.range(
d3
.quantize(t => d3.interpolateSpectral(t * 0.8 + 0.1), data.length)
.reverse()
);

const radius = (Math.min(width, height) / 2) * 0.8;

const arc = d3
.arc()
.innerRadius(0)
.outerRadius(Math.min(width, height) / 2 - 1);

const arcLabel = d3
.arc()
.innerRadius(radius)
.outerRadius(radius);

const svg = d3
.create("svg")
.attr("viewBox", [-width / 2, -height / 2, width, height]);

svg
.append("g")
.attr("stroke", "white")
.selectAll("path")
.data(arcs)
.join("path")
.attr("fill", d => color(d.data.name))
.attr("d", arc);

svg
.append("g")
.attr("font-family", "sans-serif")
.attr("font-size", 12)
.attr("text-anchor", "middle")
.selectAll("text")
.data(arcs)
.join("text")
.attr("transform", d => `translate(${arcLabel.centroid(d)})`)
.call(text =>
text
.append("tspan")
.attr("y", "-0.4em")
.attr("font-size", 10)
.text(d => d.data.name)
)
.call(text =>
text
.append("tspan")
.attr("x", 0)
.attr("y", "0.8em")
.attr("font-weight", "bold")
.attr("font-size", 15)
.text(d => formatPercent(d.data.value / totalValue))
)
.call(text =>
text
.filter(d => d.endAngle - d.startAngle > 0.25)
.append("tspan")
.attr("x", 0)
.attr("y", "2.2em")
.attr("fill-opacity", 0.7)
.attr("font-size", 10)
.text(d => formatNumber(d.data.value))
);

return svg.node();
}
Insert cell
{
const data = [
Object({ name: 'Australia', value: 5 }),
Object({ name: 'India', value: 2 }),
Object({ name: 'West Indies', value: 2 }),
Object({ name: 'England', value: 1 }),
Object({ name: 'Sri Lanka', value: 1 }),
Object({ name: 'Pakistan', value: 1 })
];
return drawPieChart(data);
}
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