我试图从visjs迁移到d3js,因为visjs总是以不同的方式重绘相同的数据。我面临的问题是d3js将我的节点彼此拉得太近,因此标签彼此重叠(请参见屏幕截图)。
对于初学者来说,D3js不是一个简单的工具,但是我敢肯定有某种方法可以解决此问题。请帮忙解决。
const links = edges.map((edge) => ({source: edge.from, target: edge.to}));
function getNodeColor(node) {
return node.color.background;
}
const width = 1000;
const height = 800;
const svg = d3.select('svg');
svg.selectAll('*').remove();
svg.attr('width', width).attr('height', height);
// simulation setup with all forces
const linkForce = d3
.forceLink()
.id(function (link) {
return (link as NetworkNode).id;
})
.strength(function (link) {
return 1;
});
const simulation = d3
.forceSimulation()
.force('link', linkForce)
.force('charge', d3.forceManyBody().strength(-120))
.force('center', d3.forceCenter(width / 2, height / 2));
const linkElements = svg
.append('g')
.attr('class', 'links')
.selectAll('line')
.data(links)
.enter()
.append('line')
.attr('stroke-width', 1)
.attr('stroke', 'rgba(50, 50, 50, 0.2)');
const nodeElements = svg
.append('g')
.attr('class', 'nodes')
.selectAll('circle')
.data(nodes)
.enter()
.append('circle')
.attr('r', 10)
.attr('fill', getNodeColor);
const textElements = svg
.append('g')
.attr('class', 'texts')
.selectAll('text')
.data(nodes)
.enter()
.append('text')
.text(function (node) {
return node.label;
})
.attr('font-size', 15)
.attr('dx', 15)
.attr('dy', 4);
simulation.nodes(nodes).on('tick', () => {
nodeElements
.attr('cx', function (node) {
return node.x;
})
.attr('cy', function (node) {
return node.y;
});
textElements
.attr('x', function (node) {
return node.x;
})
.attr('y', function (node) {
return node.y;
});
linkElements
.attr('x1', function (link) {
return (link as d3.SimulationLinkDatum<any>).source.x;
})
.attr('y1', function (link) {
return (link as d3.SimulationLinkDatum<any>).source.y;
})
.attr('x2', function (link) {
return (link as d3.SimulationLinkDatum<any>).target.x;
})
.attr('y2', function (link) {
return (link as d3.SimulationLinkDatum<any>).target.y;
});
});
// @ts-ignore
simulation.force('link').links(links);