数据可视化【十一】树状图
Constructing a node-link tree visualization
首先將節(jié)點(diǎn)之間的連線畫出來(lái)。
使用json函數(shù)讀取文件以后,使用hierarchy等函數(shù)得到連線的數(shù)組,然后綁定這個(gè)數(shù)組,給每個(gè)元素添加一個(gè)path,繪畫使用的是一個(gè)函數(shù)linkHorizontal(因?yàn)檫@里是水平的樹(shù)狀圖,如果你想繪制垂直的也可以使用linkVertical,需要注意的是,水平的需要交換每個(gè)連線的x和y,垂直的不需要)
index.js
style.css
path {fill: none;stroke: #f7a4a4; }Adding text labels to the nodes
通過(guò)root.descendants獲得每個(gè)節(jié)點(diǎn)的位置數(shù)組,綁定這個(gè)數(shù)組以后添加text,同樣需要注意水平的x和y需要分開(kāi)。然后使用一些技巧使得文字變得更加好看
const treeLayout = tree().size([Height, Width]);json('data.json').then(data =>{const root = hierarchy(data);const links = treeLayout(root).links();const linkPathGenerator = linkHorizontal().x(d => d.y).y(d => d.x)//上面的x和y進(jìn)行了替換,是因?yàn)槲覀兿胍L制水平的樹(shù)狀圖,如果使用垂直的,x和y應(yīng)該是對(duì)應(yīng)的g.selectAll('path').data(links).enter().append('path').attr('d', linkPathGenerator);g.selectAll('text').data(root.descendants()).enter().append('text').attr('x', d => d.y).attr('y', d => d.x).text(d => d.data.data.id);});Using the Margin Convention(約定)
為了讓文字布局更加好看,我們需要設(shè)置Margin來(lái)設(shè)置邊框
const margin = {top:0, right: 70, bottom: 0, left:90}; const innerWidth = width - margin.left - margin.right; const innerHeight = height - margin.top - margin.bottom;const treeLayout = tree().size([innerHeight, innerWidth]);const zoomG = svg.attr('width', width).attr('height', height).append('g');const g = zoomG.append('g') .attr('transform',`translate(${margin.left},${margin.top})`);然后后面都在g上添加元素即可。這里設(shè)置了兩層g實(shí)際上是為了后面放大縮小的時(shí)候使用
Tweaking(調(diào)整) label alignment(隊(duì)列) and size
我們還需要設(shè)置標(biāo)簽的位置,標(biāo)簽的字體大小:
index.js
style.css
text {text-shadow: /* 給標(biāo)簽添加白色的陰影,這樣就不會(huì)被線擋住 */-1px -1px 3px white,-1px 1px 3px white,1px -1px 3px white,1px 1px 3px white;pointer-events: none; /* 鼠標(biāo)經(jīng)過(guò)文字的時(shí)候不會(huì)變成可編輯的樣子(因?yàn)楸緛?lái)就是不可編輯的) */ }Panning & Zooming
這個(gè)和以前一樣,在call函數(shù)里面添加zoom函數(shù):
index.js
Curran說(shuō)弄兩層g這樣就可以解決放大再縮小以后邊框丟失的問(wèn)題,但是我發(fā)現(xiàn)好像并沒(méi)有什么卵用。。。
Using a custom font
選擇一個(gè)好看的字體也很重要,首先在Google Fonts里面找到一個(gè)喜歡的字體,然后點(diǎn)擊select
然后把link放在html文件里面,后面的字體放在對(duì)應(yīng)的選擇器里面就可以了。
效果圖:
代碼地址:https://vizhub.com/Edward-Elric233/706152caf5ca4aae992cc371f2d5891a
總結(jié)
以上是生活随笔為你收集整理的数据可视化【十一】树状图的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 做试管婴儿男方要做哪些检查
- 下一篇: 鱼人怎么样,我想买