D3径向树状图仅显示部分
我根据 Mike Bostock 在 Observable 中的示例创建了下面的代码(我知道它与原始 d3/javascript 不同)https://observablehq.com/@d3/radial-dendrogram
然而,它:
- 仅当我删除 return svg.attr("viewBox", autoBox).node(); 时才显示;在图表功能的末尾。我怀疑这导致了以下问题
- 剪得很紧
- 看起来中心在屏幕左上角的坐标 0,0 处,所以四分之三的可视化不在屏幕上。我曾尝试添加转换翻译,但这无济于事
任何想法都热烈欢迎...
索引.html
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css" href="//fonts.googleapis.com/css?family=Open+Sans" />
<script src="https://d3js.org/d3.v6.js"></script>
<link rel="shortcut icon" href="#">
<title>Radial Dendrogram</title>
</head>
<body>
<div>
</div>
<script src = 'script.js'></script>
</body>
</html>
脚本.js
function chart(birdDataSet) {
const root = tree(d3.hierarchy(birdDataSet)
.sort((a, b) => d3.ascending(a.data.name, b.data.name)));
svg.append("g")
.attr("fill", "none")
.attr("stroke", "#555")
.attr("stroke-opacity", 0.4)
.attr("stroke-width", 1.5)
.selectAll("path")
.data(root.links())
.join("path")
.attr("d", d3.linkRadial()
.angle(d => d.x)
.radius(d => d.y));
svg.append("g")
.selectAll("circle")
.data(root.descendants())
.join("circle")
.attr("transform", d => `
rotate(${d.x * 180 / Math.PI - 90})
translate(${d.y},0)
`)
.attr("fill", d => d.children ? "#555" : "#999")
.attr("r", 2.5);
svg.append("g")
.attr("font-family", "sans-serif")
.attr("font-size", 10)
.attr("stroke-linejoin", "round")
.attr("stroke-width", 3)
.selectAll("text")
.data(root.descendants())
.join("text")
.attr("transform", d => `
rotate(${d.x * 180 / Math.PI - 90})
translate(${d.y},0)
rotate(${d.x >= Math.PI ? 180 : 0})
`)
.attr("dy", "0.31em")
.attr("x", d => d.x < Math.PI === !d.children ? 6 : -6)
.attr("text-anchor", d => d.x < Math.PI === !d.children ? "start" : "end")
.text(d => d.data.name)
.clone(true).lower()
.attr("stroke", "white");
//return svg.attr("viewBox", autoBox).node();
}
function autoBox() {
document.body.appendChild(this);
const {x, y, width, height} = this.getBBox();
document.body.removeChild(this);
return [x, y, width, height];
}
width = 975
radius = width / 2
tree = d3.cluster().size([2 * Math.PI, radius - 100])
d3.json("data/flare-2.json")
.then(function(data) {
console.log(chart(data));
})
.catch(function(error) {
console.warn(error);
});
耀斑-2.json
这可以从以下地址下载
https://static.observableusercontent.com/files/e65374209781891f37dea1e7a6e1c5e020a3009b8aedf113b4c80942018887a1176ad4945cf14444603ff91d3da371b3b0d72419fa8d2ee0f6e815732475d5de?response-content-disposition=attachment%3Bfilename*%3DUTF-8%27%27flare-2.json
回答
这是一个快速重构,它消除了ObservableHQ 的疯狂并将其移动到一个简单的 HTML/JavaScript 页面。你缺少的部分是这样的:
const svg = d3
.select('svg')
.attr('width', width)
.attr('height', height)
.append('g')
.attr('transform', 'translate(' + width / 2 + ',' + height / 2 + ')');
const svg = d3
.select('svg')
.attr('width', width)
.attr('height', height)
.append('g')
.attr('transform', 'translate(' + width / 2 + ',' + height / 2 + ')');
这会调整 SVG 的大小,然后将树状图移动到 SVG 的中心。
运行代码: