用d3.js 画一个玫瑰图,每个弧都添加line图例说明,说明包括具体数据+占比,给定至少5组数据,居中显示整个图
时间: 2024-02-11 08:04:04 浏览: 24
好的,以下是用d3.js画一个玫瑰图的代码,我添加了一些注释来解释代码的功能:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>玫瑰图</title>
<script src="https://d3js.org/d3.v5.min.js"></script>
</head>
<body>
<!-- 创建一个SVG容器 -->
<svg id="chart"></svg>
<script>
const width = 600; // SVG容器的宽度
const height = 600; // SVG容器的高度
const radius = Math.min(width, height) / 2; // 玫瑰图的半径
const data = [
{name: "数据1", value: 20},
{name: "数据2", value: 30},
{name: "数据3", value: 10},
{name: "数据4", value: 25},
{name: "数据5", value: 15}
];
const colors = d3.scaleOrdinal()
.domain(data.map(d => d.name))
.range(d3.schemeCategory10); // 颜色比例尺
const svg = d3.select("#chart")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", `translate(${width / 2},${height / 2})`); // 创建SVG容器并居中
const pie = d3.pie()
.sort(null)
.value(d => d.value); // 创建饼图生成器
const arc = d3.arc()
.innerRadius(radius * 0.2) // 设置内半径为玫瑰图半径的0.2倍
.outerRadius(radius); // 设置外半径为玫瑰图半径
const arcs = svg.selectAll("g.arc")
.data(pie(data))
.enter()
.append("g")
.attr("class", "arc");
arcs.append("path")
.attr("d", arc)
.attr("fill", d => colors(d.data.name)); // 绘制玫瑰图
arcs.append("line")
.attr("x1", 0)
.attr("y1", 0)
.attr("x2", d => {
const centroid = arc.centroid(d);
const midAngle = Math.atan2(centroid[1], centroid[0]);
const x = Math.cos(midAngle) * (radius * 0.6);
return x;
})
.attr("y2", d => {
const centroid = arc.centroid(d);
const midAngle = Math.atan2(centroid[1], centroid[0]);
const y = Math.sin(midAngle) * (radius * 0.6);
return y;
})
.attr("stroke", d => colors(d.data.name))
.attr("stroke-width", "2"); // 绘制图例线
arcs.append("text")
.attr("transform", d => {
const centroid = arc.centroid(d);
const midAngle = Math.atan2(centroid[1], centroid[0]);
const x = Math.cos(midAngle) * (radius * 0.7);
const y = Math.sin(midAngle) * (radius * 0.7);
return `translate(${x},${y})`;
})
.attr("text-anchor", d => {
const centroid = arc.centroid(d);
const midAngle = Math.atan2(centroid[1], centroid[0]);
if (midAngle < -Math.PI / 2 || midAngle > Math.PI / 2) {
return "end";
} else {
return "start";
}
})
.attr("fill", d => colors(d.data.name))
.text(d => `${d.data.name}: ${d.data.value} (${d3.format(".1%")(d.data.value / d3.sum(data, d => d.value))})`); // 绘制图例文字
</script>
</body>
</html>
```
运行代码后,你将得到一个居中显示的玫瑰图,每个弧都带有一条线和一段文字,用于说明数据和占比。