<!DOCTYPE html>
<html lang="en">
<head>
<title>d3</title>
<script type="text/javascript" src="./d3@7.js"></script>
<style type="text/css">
</style>
</head>
<body>
<div id="chart"></svg>
<script type="text/javascript">
// 数据预处理
const data = [
{ name: "Apple", value: 10 },
{ name: "Banana", value: 20 },
{ name: "Cherry", value: 30 },
{ name: "Durian", value: 40 }
];
const width = 400;
const height = 400;
const radius = Math.min(width, height) / 2 - 10;
// 颜色比例尺
const colors = d3.scaleOrdinal()
.range(["#98abc5", "#8a89a6", "#7b6888", "#6b486b"]);
// 布局
const pie = d3.pie()
.value(d => d.value);
const pieData = pie(data);
// 弧形生成器
const arcs = d3.arc()
.outerRadius(radius)
.innerRadius(0);
// SVG 元素
const svg = d3.select("#chart")
.append("svg")
.attr("width", width)
.attr("height", height);
// 弧形和标签
const arc = svg.selectAll(".arc")
.data(pieData)
.enter().append("g")
.attr("class", "arc")
.attr("transform", `translate(${width / 2}, ${height / 2})`);
arc.append("path")
.attr("d", arcs)
.attr("fill", d => colors(d.data.name));
arc.append("text")
.attr("transform", d => `translate(${arcs.centroid(d)})`)
.attr("dy", "0.35em")
.attr("text-anchor", "middle")
.text(d => d.data.name);
</script>
</body>
</html>
1.png