我正在尝试使用 d3.js v7.8.5 创建垂直树。这是vue项目中的一个组件。
这是我的代码:
<!-- VerticalTree.vue -->
<template>
<div id="chart"></div>
</template>
<script>
import * as d3 from 'd3';
export default {
name: 'Chart',
data() {
return {
margin: { top: 20, right: 20, bottom: 20, left: 20 },
width: window.innerWidth - 40, // subtract margins
height: window.innerHeight - 40, // subtract margins
i: 0,
duration: 750,
rectW: 20,
rectH: 16,
horizontalSeparationBetweenNodes: 70,
verticalSeparationBetweenNodes: 80,
url: "<redacted>",
app_count: true,
app_data: null,
root: null,
svg: null,
};
},
mounted() {
this.fetchData();
},
methods: {
fetchData() {
d3.json(this.url).then(data => {
this.createChart(data);
});
},
createChart(data) {
const svg = d3
.select('#chart')
.append('svg')
.attr('width', this.width - this.margin.right - this.margin.left)
.attr('height', this.height - this.margin.top - this.margin.bottom)
.append('g')
.attr("transform", "translate(" + this.width / 2 + "," + 20 + ")");
let treeLayout = d3.tree()
.nodeSize([this.rectW + this.horizontalSeparationBetweenNodes, this.rectH + this.verticalSeparationBetweenNodes])
.separation(function (a, b) {
return a.parent == b.parent ? 1 : 1;
});
this.root = d3.hierarchy(data);
treeLayout(this.root);
if (this.root.children) {
this.root.children.forEach(this.collapse);
}
// Draw links
svg
.selectAll('.link')
.data(this.root.links())
.enter()
.append('path')
.attr('class', 'link')
.attr("id", "links")
.attr('d', d3.linkVertical().x(d => d.x).y(d => d.y));
// Draw nodes
const nodes = svg
.selectAll('.node')
.data(this.root.descendants())
.enter()
.append('g')
.attr('class', 'node')
.attr("id", "nodes")
.attr('transform', d => `translate(${d.x},${d.y})`);
nodes
.append('circle')
.attr('r', 5)
.style('fill', 'steelblue');
nodes
.append('text')
.attr('dy', '0.31em')
.attr('x', 0)
.attr('y', d => (d.children ? -8 : 20))
.style('text-anchor', 'middle')
.text(d => d.data.name);
console.log(this.root);
},
collapse(node) {
if (node.children) {
node._children = node.children;
node._children.forEach(this.collapse);
node.children = null;
}
},
},
};
</script>
我需要使用nodeSize,因为数据是动态加载的并且可能会变化。我的根节点位置正确,但它的子节点位置不正确。检查时我发现:
我不太明白为什么 x 坐标会采用如此疯狂的值。我以前使用过 size 并使其正常工作,但我的用例不允许这样做。如果有人可以解释为什么会发生这种情况那就太好了!
如果没有工作代码,很难说清楚,但我之前遇到的一个错误是添加我希望是数字的值,结果却是字符串
即"500"+"600" = 将为您提供字符串 500600 而“500”-“600”会给你数字 -100
检查你没有这样做