d3 力导向图 force graph
生活随笔
收集整理的這篇文章主要介紹了
d3 力导向图 force graph
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
?背景:項目 vue.js + d3 v4
? ? ? ? ? 力導(dǎo)向圖可以直觀看出各個元素之間的相互作用力
數(shù)據(jù):
{nodes:[{id:xxx, group: xx},{},...] // nodes 是每個節(jié)點 group 是聚類后的分組 為了讓每個 circle 顯示不同分組的顏色links:[{target:xxx, source:xxx, value:xx },...] // links 為連線 value 可以代表 line 的 stroke-width }復(fù)制代碼具體的代碼就不貼了,官網(wǎng)很多 demo 都可以直接拿來用
效果如下:
在這里介紹幾個點..
1.有的時候我們需要讓他們之間分隔的間隔大一點,需要修改的地方:
var simulation = d3.forceSimulation().force("link", d3.forceLink().id(function(d) {return d.id;})).force("charge", d3.forceManyBody().strength(-200).distanceMax(100)) // strength 默認(rèn) -30.force("center", d3.forceCenter(width / 2, height / 2)); 復(fù)制代碼2.當(dāng)我們鼠標(biāo)移到某個點的時候,想讓與之相連的 circle fill + line stroke 高亮顯示:
這里注意一下 鼠標(biāo)移出的時候 樣式恢復(fù)到之前的樣式
ps:我們的link數(shù)據(jù)有一些重復(fù)的,所以要考慮到 target 和 source 相反的情況
.on("mouseover", function(d, i, o) {let currentd = d.idvar connectedNodeIds = graph.links.filter(x => x.source.id == d.id || x.target.id == d.id).map(x => x.source.id == d.id ? x.target.id : x.source.id)d3.select(".nodes").selectAll("circle").attr("fill", function(c) {if (connectedNodeIds.indexOf(c.id) > -1 || c.id == d.id) return "red";else return '#e49433'})d3.select(".links").selectAll("line").style("stroke", function(d,c) {if ((d.target.id === currentd && connectedNodeIds.indexOf(d.source.id) > -1) || (d.source.id === currentd && connectedNodeIds.indexOf(d.target.id) > -1)) {return 'red'} else {return '#999'}})}).on("mouseout", function(d) {d3.select(".nodes").selectAll("circle").attr("fill", "#e49433");d3.select(".links").selectAll("line").style("stroke", '#999')}) 復(fù)制代碼參考鏈接
參考鏈接2
mouseover參考鏈接
總結(jié)
以上是生活随笔為你收集整理的d3 力导向图 force graph的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Hyperledger Fabric 1
- 下一篇: 一出好戏不止是部电影,它也正接近你的生活