D3.js实现3D饼图
时间: 2023-10-24 22:09:06 浏览: 183
作为一名AI助手,我无法展示图形,但我可以提供D3.js实现3D饼图的代码,供您参考:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>D3 3D Pie Chart</title>
<script src="https://d3js.org/d3.v5.min.js"></script>
</head>
<body>
<script>
var width = 500;
var height = 500;
var radius = Math.min(width, height) / 2;
var depth = 30;
var color = d3.scaleOrdinal(d3.schemeCategory10);
var data = [
{label: "A", value: 20},
{label: "B", value: 30},
{label: "C", value: 50}
];
var svg = d3.select("body")
.append("svg")
.attr("width", width)
.attr("height", height);
var pie = d3.pie()
.sort(null)
.value(function(d) { return d.value; });
var arc = d3.arc()
.outerRadius(radius - 10)
.innerRadius(0);
var arc3d = d3.arc()
.outerRadius(radius - 10)
.innerRadius(0)
.startAngle(function(d) { return d.startAngle; })
.endAngle(function(d) { return d.endAngle; });
var pieData = pie(data);
var g = svg.append("g")
.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");
var path = g.selectAll("path")
.data(pieData)
.enter().append("path")
.attr("fill", function(d, i) { return color(i); })
.attr("d", arc);
path.on("mouseover", function(d) {
var path3d = d3.select(this)
.transition()
.duration(200)
.attr("d", arc3d);
path3d.append("svg:title").text(d.data.label + " - " + d.data.value + "%");
});
path.on("mouseout", function(d) {
d3.select(this)
.transition()
.duration(200)
.attr("d", arc);
});
var paths = d3.selectAll("path");
var zScale = d3.scaleLinear()
.domain([0, paths.size()])
.range([0, depth]);
paths.each(function(d, i) {
var path = d3.select(this);
var prev = path.attr("d");
var next = prev.replace("A", "L");
var pos1 = prev.indexOf("A");
var pos2 = prev.indexOf(" ", pos1) + 1;
var pos3 = prev.indexOf(",", pos2) + 1;
var pos4 = prev.indexOf(" ", pos3) + 1;
var pos5 = prev.indexOf(",", pos4) + 1;
var slice = prev.substring(pos1, pos2);
var rx = prev.substring(pos2, pos3 - 1);
var ry = prev.substring(pos3, pos4 - 1);
var largeArc = prev.substring(pos4, pos5 - 1);
var sweep = prev.substring(pos5, prev.indexOf(" ", pos5));
var endAngle = d.endAngle;
var startAngle = d.startAngle;
var midAngle = startAngle + (endAngle - startAngle) / 2;
var x1 = Math.cos(midAngle) * (radius - 10);
var y1 = Math.sin(midAngle) * (radius - 10);
var x2 = Math.cos(midAngle) * (radius - 10 + zScale(i));
var y2 = Math.sin(midAngle) * (radius - 10 + zScale(i));
next += "L" + x1 + "," + y1 + " ";
next += "L" + x2 + "," + y2 + " ";
var center = arc.centroid(d);
center[2] = zScale(i);
next += "A" + rx + "," + ry + " " + largeArc + " " + sweep + " " + center[0] + "," + center[1];
path.attr("d", next);
});
</script>
</body>
</html>
```
这个代码会生成一个3D饼图,其中包含三个部分,分别对应数据中的A、B、C。当鼠标移动到图形上时,会显示当前部分的标签和占比。
阅读全文