Published
Edited
Nov 18, 2020
3 forks
Insert cell
md`# D3 Donut Chart`
Insert cell
d3 = require('d3@5')
Insert cell
USData = [
{ type: 'Poultry', value: 48.9954 },
{ type: 'Beef', value: 25.9887 },
{ type: 'Pig', value: 22.9373 },
{ type: 'Sheep', value: 50.4869 }
]
Insert cell
height = 500
Insert cell
width = 900
Insert cell
colorScale = {
const colors = [ '#976393', '#685489', '#43457f', '#ff9b83' ]
return d3.scaleOrdinal( USData.map(d => d.type), colors )
}
Insert cell
arc = d3.arc()
.innerRadius( 0.5 * height / 2 )
.outerRadius( 0.85 * height / 2 )
Insert cell
pie = d3.pie()
.value(d => d.value)
Insert cell
labelArcs = d3.arc()
.innerRadius( 0.95 * height /2 )
.outerRadius( 0.95 * height / 2 )
Insert cell
pieArcs = pie( USData )
Insert cell
donutChart = {
const svgHTML = html`<svg width="900" height="550" />`
const svg = d3.select(svgHTML)
svg.append('g')
.attr('class', 'donut-container')
.attr('transform', `translate(${ width / 2 }, ${ height / 2})` )
.selectAll('path')
.data(pieArcs)
.join('path')
.style('stroke', 'white')
.style('stroke-width', 2)
.style('fill', d => colorScale( d.data.type ))
.attr('d', arc)
const text = svg.append('g')
.attr('class', 'lablels-container')
.attr('transform', `translate(${width/2},${height/2})`)
.selectAll('text')
.data(pieArcs)
.join('text')
.attr('transform', d => `translate(${ labelArcs.centroid(d) })`)
.attr('text-anchor', 'middle')
text.selectAll('tspan')
.data( d => [
d.data.type,
d.data.value.toFixed(1) + 'kg'
])
.join('tspan')
.attr('x', 0)
.style('font-family', 'sans-serif')
.style('font-size', 12)
.style('font-weight', (d,i) => i ? undefined : 'bold')
.style('fill', '#222')
.attr('dy', (d,i) => i ? '1.2em' : 0)
.text(d => d)
return svgHTML
}
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