console
// 数据
const data = [
{ label: '苹果', value: 30 },
{ label: '香蕉', value: 20 },
{ label: '橙子', value: 15 },
{ label: '葡萄', value: 35 }
];
// 选择SVG元素
const svg = d3.select('#pie-chart');
const width = 400;
const height = 400;
const radius = Math.min(width, height) / 2;
// 设置SVG的尺寸
svg.attr('width', width).attr('height', height);
// 创建一个分组元素,将饼图放在中心
const g = svg.append('g')
.attr('transform', `translate(${width / 2},${height / 2})`);
// 定义一个弧生成器
const arc = d3.arc()
.innerRadius(0)
.outerRadius(radius);
// 定义一个饼图布局
const pie = d3.pie()
.value(d => d.value);
// 对数据进行处理,生成饼图所需的角度信息
const pieData = pie(data);
// 添加线性渐变定义
const gradient = svg.append('linearGradient')
.attr('id', 'pie-gradient');
gradient.append('stop')
.attr('offset', '0%')
.attr('stop-color', 'lightblue');
gradient.append('stop')
.attr('offset', '100%')
.attr('stop-color', 'blue');
// 为每个扇形添加路径元素,并使用渐变填充
const paths = g.selectAll('path')
.data(pieData)
.join('path')
.attr('d', arc)
.attr('fill', 'url(#pie-gradient)');
// 添加标签(这部分相对复杂,这里简单示例,实际应用可能需更精细布局)
const labels = g.selectAll('text')
.data(pieData)
.join('text')
.attr('transform', d => `translate(${arc.centroid(d)})`)
.text(d => data[pieData.indexOf(d)].label);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>D3.js Pie Chart</title>
<script src="https://cdn.bootcdn.net/ajax/libs/d3/7.9.0/d3.min.js"></script>
<style>
/* 为饼图的扇形设置样式 */
path {
stroke: white;
stroke-width: 2px;
}
</style>
</head>
<body>
<svg id="pie-chart"></svg>
<script src="script.js"></script>
</body>
</html>
/* 定义一个线性渐变 */
#pie-chart linearGradient {
x1: 0%;
y1: 0%;
x2: 100%;
y2: 0%;
}
#pie-chart linearGradient stop:first-child {
stop-color: lightblue;
}
#pie-chart linearGradient stop:last-child {
stop-color: blue;
}