Published
Edited
Feb 13, 2021
2 stars
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
chart = {
// Define variables for this cell (one for each visual element you'll create)
let arcs, svg;

arcs = pie(
data.filter(d => {
if (census_year == 2019) {
return d.year_measured == 2019;
} else if (census_year == 2017) {
return d.year_measured == 2017;
}
})
);

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.group))
.attr("d", arc)
.append("title")
.text(d => `${d.data.group}: ${d.data.pop.toLocaleString()}`);

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-weight", "bold")
.text(d => d.data.group)
)
.call(text =>
text
.filter(d => d.endAngle - d.startAngle > 0.25)
.append("tspan")
.attr("x", 0)
.attr("y", "0.7em")
.attr("fill-opacity", 0.7)
.text(d => d.data.pop.toLocaleString())
);

return svg.node();
}
Insert cell
Insert cell
data = d3.csvParse(
await FileAttachment("census_age_groups.csv").text(),
d3.autoType
)
Insert cell
Insert cell
width
Insert cell
height = Math.min(width, 500)
Insert cell
Insert cell
color = d3
.scaleOrdinal()
.domain(data.map(d => d.group))
.range(
d3
.quantize(t => d3.interpolateSpectral(t * 0.8 + 0.1), data.length)
.reverse()
)
Insert cell
Insert cell
arc = d3
.arc()
.innerRadius(function() {
if (chartType == 'Donut') {
return radius * 0.67;
} else {
return 0;
}
})
.outerRadius(Math.min(width, height) / 2 - 1)
Insert cell
radius = Math.min(width, height) / 2
Insert cell
pie = d3
.pie()
.padAngle(0.005)
.sort(null)
.value(d => d.pop)
Insert cell
arcLabel = {
const radius = (Math.min(width, height) / 2) * 0.8;
return d3
.arc()
.innerRadius(radius)
.outerRadius(radius);
}
Insert cell
Insert cell
d3 = require("d3@6")
Insert cell
import { select } from "@jashkenas/inputs"
Insert cell
import { radio } from "@jashkenas/inputs"
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