Public
Edited
Apr 1, 2024
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
chart = (dataset) => {
// Specify the chart’s dimensions.
const width = 1080;
const height = 720;

const innerRadius = height / 2 - 150;
const outerRadius = height / 2;

const svg = d3.create("svg").attr("width", width).attr("height", height);

const pie = d3.pie()
.padAngle(0.02)
.value(d => d.value);

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

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

const arcs = svg.selectAll("g.arc")
.data(pie(dataset))
.join('g')
.classed('arc', true)
.attr('transform', `translate(${width/2}, ${height/2})`);

arcs.append('path')
.attr('fill', (d, i) => color(i))
.attr('d', arc)
.append('title').text(d => d.data.name);

arcs.append('text')
.attr('transform', d => `translate(${arc.centroid(d)})`)
.attr('text-anchor', 'middle')
.text(d => d.value)
.style('fill', 'purple');

svg.append('text')
.attr('transform', `translate(${width/2}, ${height/2-50})`)
.attr('text-anchor', 'middle')
.attr('alignment-baseline', 'middle')
.text('Hours per Week')
.style('font-size', '16pt');

const legendScale = d3
.scaleOrdinal()
.domain(dataset.map((d) => d.name))
.range(d3.quantize(t => d3.interpolateSpectral(t * 0.8 + 0.1), dataset.length).reverse());
var legendOrdinal = d3Legend
.legendColor()
.shape("path", d3.symbol().type(d3.symbolSquare).size(60)())
.shapePadding(20)
.orient("vertical")
.scale(legendScale);

svg.append("g").attr("transform", `translate(${width/2-50},${height/2})`).call(legendOrdinal);

return svg.node();
}
Insert cell
dataset = await FileAttachment("my-data.csv").csv({typed: true});
Insert cell
my-data.csv
Type Table, then Shift-Enter. Ctrl-space for more options.

Insert cell
d3 = require("d3@7")
Insert cell
d3Legend = require('d3-svg-legend')
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