写一个html画桑基图
时间: 2023-12-18 09:05:54 浏览: 146
好的,以下是一个简单的 HTML 代码来画桑基图:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Sankey Chart</title>
<script src="https://d3js.org/d3.v5.min.js"></script>
</head>
<body>
<div id="chart"></div>
<script>
var data = {
nodes: [
{node: 0, name: "Node 0"},
{node: 1, name: "Node 1"},
{node: 2, name: "Node 2"},
{node: 3, name: "Node 3"},
{node: 4, name: "Node 4"}
],
links: [
{source: 0, target: 2, value: 10},
{source: 1, target: 3, value: 20},
{source: 2, target: 3, value: 5},
{source: 2, target: 4, value: 8},
{source: 3, target: 4, value: 15}
]
}
var margin = {top: 10, right: 10, bottom: 10, left: 10},
width = 600 - margin.left - margin.right,
height = 400 - margin.top - margin.bottom;
var svg = d3.select("#chart").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform",
"translate(" + margin.left + "," + margin.top + ")");
var sankey = d3.sankey()
.size([width, height])
.nodeWidth(15)
.nodePadding(10)
.align("left")
.nodes(data.nodes)
.links(data.links)
.layout(32);
var link = svg.append("g")
.selectAll(".link")
.data(data.links)
.enter().append("path")
.attr("class", "link")
.attr("d", sankey.link())
.style("stroke-width", function(d) { return Math.max(1, d.dy); })
.sort(function(a, b) { return b.dy - a.dy; });
link.append("title").text(function(d) { return d.source.name + " → " + d.target.name + "\n" + d.value; });
var node = svg.append("g")
.selectAll(".node")
.data(data.nodes)
.enter().append("g")
.attr("class", "node")
.attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; })
.call(d3.drag()
.subject(function(d) { return d; })
.on("start", function() { this.parentNode.appendChild(this); })
.on("drag", dragmove));
node.append("rect")
.attr("height", function(d) { return d.dy; })
.attr("width", sankey.nodeWidth())
.style("fill", "#ddd")
.style("stroke", "#000");
node.append("text")
.attr("x", -6)
.attr("y", function(d) { return d.dy / 2; })
.attr("dy", ".35em")
.attr("text-anchor", "end")
.attr("transform", null)
.text(function(d) { return d.name; })
.filter(function(d) { return d.x < width / 2; })
.attr("x", 6 + sankey.nodeWidth())
.attr("text-anchor", "start");
function dragmove(d) {
d3.select(this)
.attr("transform",
"translate("
+ d.x + ","
+ (d.y = Math.max(
0, Math.min(height - d.dy, d3.event.y))
) + ")");
sankey.relayout();
link.attr("d", sankey.link());
}
</script>
</body>
</html>
```
请注意,您仍需要引入 D3.js JavaScript 库以使此代码正常工作。
阅读全文