Public
Edited
Oct 12, 2023
Insert cell
Insert cell
chart = {
const height = Math.min(width, 500);
const radius = Math.min(width, height) / 2;

//圆弧生成器,设置内径、外径
const arc = d3.arc()
.innerRadius(radius * 0.67)
.outerRadius(radius - 1);
//饼图生成器,调用pie(data)可以计算出每一块的开始、结束弧度
const pie = d3.pie()
.padAngle(1 / radius)
.sort(null)
.value(d => d.value);

//颜色尺子,参考pie plot
const color = d3.scaleOrdinal()
.domain(data.map(d => d.name))
.range(d3.quantize(t => d3.interpolateSpectral(t * 0.8 + 0.1), data.length).reverse());

//svg
const svg = d3.create("svg")
.attr("width", width)
.attr("height", height)
.attr("viewBox", [-width / 2, -height / 2, width, height])
.attr("style", "max-width: 100%; height: auto;");

//采用arc绘制每一块饼,采用fill进行填充
svg.append("g")
.selectAll()
.data(pie(data))
.join("path")
.attr("fill", d => color(d.data.name))
.attr("d", arc)
.append("title")
.text(d => `${d.data.name}: ${d.data.value.toLocaleString()}`);

//绘制文本
svg.append("g")
.attr("font-family", "sans-serif")
.attr("font-size", 12)
//文本水平居中
.attr("text-anchor", "middle")
.selectAll()
.data(pie(data))
.join("text")
//计算出每一块饼的中心点坐标(x,y),中心点坐标处于圆弧的中心,也处于内径与外径的中心
.attr("transform", d => `translate(${arc.centroid(d)})`)
//第一行文本,name属性值
.call(text => text.append("tspan")
.attr("y", "-0.4em")
.attr("font-weight", "bold")
.text(d => d.data.name))
//第二行文本,value属性值,如果饼的结束-开始<0.25弧不绘制
.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.value.toLocaleString("en-US")));
return svg.node();
}
Insert cell
data = [
{
"name": "<5",
"value": 19912018
},
{
"name": "5-9",
"value": 20501982
},
{
"name": "10-14",
"value": 20679786
},
{
"name": "15-19",
"value": 21354481
},
{
"name": "20-24",
"value": 22604232
},
{
"name": "25-29",
"value": 21698010
},
{
"name": "30-34",
"value": 21183639
},
{
"name": "35-39",
"value": 19855782
},
{
"name": "40-44",
"value": 20796128
},
{
"name": "45-49",
"value": 21370368
},
{
"name": "50-54",
"value": 22525490
},
{
"name": "55-59",
"value": 21001947
},
{
"name": "60-64",
"value": 18415681
},
{
"name": "65-69",
"value": 14547446
},
{
"name": "70-74",
"value": 10587721
},
{
"name": "75-79",
"value": 7730129
},
{
"name": "80-84",
"value": 5811429
},
{
"name": "≥85",
"value": 5938752
}
]
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