Published
Edited
Apr 1, 2022
4 forks
Insert cell
# Simple Pie Chart
Insert cell
pieChart = {
const svg = d3.create('svg').attr('height', sizes.height).attr('width', sizes.width)
const container = svg.append('g').attr('transform', `translate(${sizes.width/2}, ${sizes.height/2})`)

const colors = d3.scaleOrdinal()
.domain(data.map(d => d.name))
.range(d3.schemeCategory10)
const pie = d3.pie()
const pieData = pie.value(d=> d.value)(data)
const segments = d3.arc()
.innerRadius(80)
.outerRadius(170)
.padAngle(.5)
.padRadius(10)
.cornerRadius(4)

//Rendering sections
let sections = container.selectAll('path').data(pieData, d => d.data.name)
sections.exit().remove()
const sectionsEnter = sections.enter().append('path').attr("d", segments).attr('fill', d => colors(d.data.name))
sections = sectionsEnter.merge(sections)

sections
.on('mouseover', function() {
d3.select(this).transition().duration(500).attr('transform', 'scale(1.05)')
})
.on('mouseout', function() {
d3.select(this).transition().duration(500).attr('transform', 'scale(1)')
})
return svg.node()
}
Insert cell
## Sizes
Insert cell
sizes = ({height: 400, width: 400})
Insert cell
## Data
Insert cell
data = [{name: 'Apples', value: 30}, {name: 'Bananas', value: 60}, {name: 'Oranges', value: 10}]
Insert cell
## Utils
Insert cell
d3 = require('d3')

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