我正在开发一个 D3 Force 布局,它将不同的国家/地区显示为圆圈,并将共享边界的国家/地区显示为各自节点之间的链接。
这是数据集 https://raw.githubusercontent.com/DealPete/forceDirected/master/countries.json
这是代码笔 http://codepen.io/redixhumayun/pen/ZLELvG?editors=0010
由于某种原因,节点显示,但我的链接没有显示。当我使用 DevTools 检查它们时,它们的位置为 0x0。我不知道这是为什么。
这是相关代码。
//Creating force layout simulation object
var simulation = d3.forceSimulation(data_nodes)
.force('link', d3.forceLink().id(function(d){ return d.id }))
.force('charge', d3.forceManyBody())
.force('center', d3.forceCenter(width / 2, height / 2));
//creating a variable for the links where the data will be stored
var link = svg.selectAll('.link')
.append('g')
.data(data_links)
.enter().append('line')
.attr('class', 'link')
.attr('stroke-width', function(d){ return 8 })
simulation
.nodes(data_nodes)
.on('tick', ticked);
simulation.force('link')
.links(link);
function ticked(){
link.attr('x1', function(d){ return d.source.x; })
.attr('y1', function(d){ return d.source.y; })
.attr('x2', function(d){ return d.target.x; })
.attr('y2', function(d){ return d.target.y; });
node.attr('cx', function(d) { return d.x; })
.attr('cy', function(d) { return d.y; })
.on('mouseover', function(d){
console.log(d.country);
})
}
最佳答案
只需设置线条的颜色:
.attr("stroke", "black")
除此之外,由于您的 links
数组使用节点的数字索引,因此您无需在强制中设置 id
:
.id(function(d){ return d.id })
这是您更新的 CodePen:http://codepen.io/anon/pen/qRExJe?editors=0010
关于javascript - 链接未显示在 D3 v4 强制布局中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41479095/