D3 v4.x入門(1-7)—— 樹狀圖探究
阿新 • • 發佈:2019-01-26
樹狀圖,一般用於樹形結構資料展示(廢話呢麼),下面原始碼實現上圖效果
<template> <div id='svgContainer' style=""> <div class="every"> <h3>樹狀圖探究</h3> <div class="svg" id="chordDiagram"></div> </div> </div> </template> <script> import * as d3 from 'd3' export default { data () { return { treeData: { 'name': '中國', 'children': [ { 'name': '浙江', 'children': [ {'name': '杭州'}, {'name': '寧波'}, {'name': '溫州'}, {'name': '紹興'} ] }, { 'name': '廣西', 'children': [ { 'name': '桂林', 'children': [ {'name': '秀峰區'}, {'name': '疊彩區'}, {'name': '象山區'}, {'name': '七星區'} ] }, {'name': '南寧'}, {'name': '柳州'}, {'name': '防城港'} ] }, { 'name': '黑龍江', 'children': [ {'name': '哈爾濱'}, {'name': '齊齊哈爾'}, {'name': '牡丹江'}, {'name': '大慶'} ] }, { 'name': '新疆', 'children': [ {'name': '烏魯木齊'}, {'name': '克拉瑪依'}, {'name': '吐魯番'}, {'name': '哈密'} ] } ] } }, methods: { treeDiagram () { // 樹狀圖因為預設是上往下渲染的,改成從左往右渲染後會發現width和height都倒過來了,可以看具體引數的細節 let width = 400 let height = 400 let _this = this let svg = d3.select('#treeDiagram') .append('svg') .attr('width', width) .attr('height', height) // 初始化樹狀圖資料獲取器 let tree = d3.tree() .size([width, height - 80]) .separation(function (a, b) { return (a.parent === b.parent ? 1 : 2) / a.depth }) // 初始化json資料轉成一棵樹,這個步驟是非常必要的!! let hierarchyData = d3.hierarchy(_this.treeData) .sum(function (d) { return d.value }) // 初始化樹狀圖 let treeData = tree(hierarchyData) // 獲取節點 let nodes = treeData.descendants() // 獲取邊,也就是連線 let links = treeData.links() // 繪製線 let g = svg.append('g').attr('transform', 'translate(40,0)') g.selectAll('.link') .data(links) .enter().append('path') .attr('class', 'link') .style('fill', '#cccccc') .attr('d', d3.linkHorizontal() .x(function (d) { return d.y }) .y(function (d) { return d.x })) // 繪製文字和節點 g.selectAll('.node') .data(nodes) .enter().append('g') .attr('class', function (d) { return 'node' + (d.children ? ' node--internal' : ' node--leaf') }) .attr('transform', function (d) { return 'translate(' + d.y + ',' + d.x + ')' }) g.selectAll('.node').append('circle') .attr('r', 5) .style('fill', 'green') g.selectAll('.node').append('text') .attr('dy', 3) .attr('x', function (d) { return d.children ? -8 : 8 }) .style('text-anchor', function (d) { return d.children ? 'end' : 'start' }) .text(function (d) { return d.data.name }) .style('font-size', '11px') } }, mounted () { this.treeDiagram () } } </script> <style lang="less"> #svgContainer{ width: 100%; height: 100%; .every{ width: 400px; height: 425px; margin:15px; float: left; h3{ margin:0; .button{ float: right; margin-right: 20px; font-size: 14px; cursor: pointer; padding: 2px 8px; border:1px solid #ccc; background: yellowgreen; border-radius: 4px; &:hover{ background: violet; } } } .svg{ width: 400px; height: 400px; } } } </style>