d3.js 入門學習記錄(九) 用佈局實現餅圖 堆疊面積圖 矩陣樹圖 思維樹圖 封閉圖

WanFengZ發表於2019-11-29

餅圖

在建立弧度區域時,我們呼叫 d3.arc() 常常需要資料項內有固定在 [0, 2 * Math.PI] 的值來指定弧度片段的起始角度,但是實際上我們的資料內只有資料數值,d3.pie() 就可以幫我們實現對資料的結構的轉化。這種性質的方法被稱為佈局。

pie的相關配置方法如下

  1. pie.value() - 設定值訪問器,用來指定拿來計算角度的屬性值。
  2. pie.sort() - 設定排序比較器,實現資料的排序。
  3. pie.sortValues() - 設定排序比較器,函式的引數 a,b 是通過值訪問器取值後的。
  4. pie.startAngle() - 設定所有環形的起始角度。
  5. pie.endAngle() - 設定所有環形的終止角度。
  6. pie.padAngle() - 設定相鄰兩個環之間的間隙角度。
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        .pie text{
            fill: white;
            font-weight: bold;
        }
    </style>
</head>
<body>
<script src="../d3.js"></script>
<script>
    function pieChart() {
        const _chart = {}

        let _width = 500,
            _height = 500,
            _colors = d3.scaleOrdinal(d3.schemeCategory10),
            _data = [],
            _svg,
            _body,
            _pie,
            _radius = 200  ,
            _innerRadius = 100,
            _duration = 1000
           

        _chart.data = function (d) {
            if (!arguments.length) return _data;
            _data = d;
            return _chart;
        }

        _chart.render = function () {
            if (!_svg) {
                _svg = d3.select('body')
                  .append('svg')
                  .attr('width', _width)
                  .attr('height', _height)
            }

            renderBody()
        }

        function renderBody() {
            if (!_body) {
                _body = _svg.append('g')
                  .classed('body', true)
            }
            renderPie()
        }

        function renderPie() {
            const pie = d3.pie()
              .sort((a, b) => b.id - a.id)
              .value(d => d.value)

            const arc = d3.arc()
              .outerRadius(_radius)
              .innerRadius(_innerRadius)

            if (!_pie) {
                _pie = _body.append('g')
                  .classed('pie', true)
                  .attr('transform', `translate(${_radius}, ${_radius})`)
            }

            renderSlices(pie, arc)
            renderLabels(pie, arc)
        }

        function renderSlices(pie, arc) {
            const slices = _pie.selectAll('path.arc')
                .data(pie(_data))

            slices.enter()
                .append('path')
                .merge(slices)
                    .classed('arc', true)
                    .attr('fill', (d, i) => _colors(i))
                    .transition().duration(_duration)
                        .attrTween('d', function (d) {
                            const currentArc = this.__current__ || {startAngle: 0, endAngle: 0}
                            const interpolate = d3.interpolate(currentArc, d)
                            this.__current__ = d
                            return t => arc(interpolate(t))
                        })

        }

        function renderLabels(pie, arc) {
            const labels = _pie.selectAll('text.label').data(pie(_data))

            labels.enter()
                .append('text')
                .merge(labels)
                    .attr('class', 'label')
                    .transition().duration(_duration)
                        .attr('transform', d => `translate(${arc.centroid(d)})`)
                        .attr('dy', '.35rem')
                        .attr('text-anchor', 'middle')
                        .text(d => d.data.id)
        }

        return _chart
    }

    function randomData() {
         return Math.random() * 9 + 1;
    }

    function update() {
        for (let j = 0; j < data.length; ++j) {
            data[j].value = randomData();
        }
        chart.render();
    }

    const numberOfDataPoint = 6

    const data = d3.range(numberOfDataPoint).map(function (i) {
        return {id: i, value: randomData()};
    });

    const chart = pieChart()
        .data(data);

    chart.render();
</script>
<div class="control-group">
    <button onclick="update()">Update</button>
</div>
</body>
</html>
複製程式碼

效果如下:

d3.js 入門學習記錄(九) 用佈局實現餅圖 堆疊面積圖 矩陣樹圖 思維樹圖 封閉圖

我們定義了一個 pie 佈局器,指定 id 值大的排在前,資料中的 value 屬性值作為計算弧角度的值。

 const pie = d3.pie()
    .sort((a, b) => b.id - a.id)
    .value(d => d.value)
複製程式碼

然後我們在繫結資料中繫結的都是 pie(_data) 處理後的資料,他會幫我們生成形如 [{startAngle: , endAngle: }, ...] 的資料便於給 arc 處理。

另外我們在設定扇形的過渡時,把當前的資料項存於 dom 上,然後每次更新都檢查是否有之前的資料,如果有,就從之前的角度開始過渡變化,這讓餅圖的過渡效果更好。

.attrTween('d', function (d) {
    const currentArc = this.__current__ || {startAngle: 0, endAngle: 0}
    const interpolate = d3.interpolate(currentArc, d)
    this.__current__ = d
    return t => arc(interpolate(t))
})
複製程式碼

堆疊面積圖

[
  {month: new Date(2015, 0, 1), apples: 3840, bananas: 1920, cherries: 960, dates: 400},
  {month: new Date(2015, 1, 1), apples: 1600, bananas: 1440, cherries: 960, dates: 400},
  {month: new Date(2015, 2, 1), apples:  640, bananas:  960, cherries: 640, dates: 400},
  {month: new Date(2015, 3, 1), apples:  320, bananas:  480, cherries: 640, dates: 400}
]
複製程式碼

d3.stack() 可以幫我們把上面的資料型別轉為下面的資料型別來便於繪製堆疊面積圖。

[
  [[   0, 3840], [   0, 1600], [   0,  640], [   0,  320]], // apples
  [[3840, 5760], [1600, 3040], [ 640, 1600], [ 320,  800]], // bananas
  [[5760, 6720], [3040, 4000], [1600, 2240], [ 800, 1440]], // cherries
  [[6720, 7120], [4000, 4400], [2240, 2640], [1440, 1840]], // dates
]
複製程式碼

相關配置方法如下:

  1. stack.keys() - 設定 keys 訪問器, 指定需要處理的屬性。

  2. stack.order() - 設定排序訪問器,內建以下:

    d3.stackOrderAscending - 將和最小的值的序列放在底部.

    d3.stackOrderDescending - 將和最大的值的序列放在底部.

    d3.stackOrderInsideOut - 和越大越靠近中間.

    d3.stackOrderNone - 使用原始資料的順序不進行順序調整.

    d3.stackOrderReverse - 將原始資料順序逆轉.

  3. stack.offset() - 設定偏移訪問器,內建以下:

    d3.stackOffsetExpand - 將基線設定為 0 並且頂線為 1.

    d3.stackOffsetDiverging - 正值在 0 之上,負值在 0 之下.

    d3.stackOffsetNone - 使用 0 基線.

    d3.stackOffsetSilhouette - 將流圖以 0 為中心居中.

    d3.stackOffsetWiggle - 最小化流圖的擺動.

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        .grid-line{
            stroke: black;
            shape-rendering: crispEdges;
            stroke-opacity: .2;
        }
        .line {
            fill: none;
            stroke: steelblue;
            stroke-width: 2;
        }
        .area {
            stroke: none;
            fill: steelblue;
            fill-opacity: .2;
        }
    </style>
</head>
<body>
<script src="../d3.js"></script>
<script>
    function stackedAreaChart() {
        const _chart = {}

        let _width = 900,
            _height = 900,
            _margins = {top: 30, right: 30, bottom: 30, left: 30},
            _x,
            _y,
            _colors = d3.scaleOrdinal(d3.schemeCategory10),
            _data = [],
            _svg,
            _body

        _chart.render = function () {
            if (!_svg) {
                _svg = d3.select('body').append('svg')
                    .attr('width', _width)
                    .attr('height', _height)

                renderAxes()
            }
            renderBody()
        }

        function renderAxes() {
            const axes = _svg.append('g')
                .classed('axes', true)

            axes.append('g')
                .classed('x-axis', true)
                .attr('transform', `translate(${_margins.left}, ${_height - _margins.bottom})`)
                .call(d3.axisBottom().scale(_x.range([0, _width - _margins.left - _margins.right])))

            axes.selectAll('g.x-axis g.tick')
                .append('line')
                    .classed('grid-line', true)
                        .attr('x1', 0)
                        .attr('y1', 0)
                        .attr('x2', 0)
                        .attr('y2', -(_height - -_margins.top - _margins.bottom))

            axes.append('g')
                .classed('y-axis', true)
                .attr('transform', `translate(${_margins.left}, ${_margins.top})`)
                .call(d3.axisLeft().scale(_y.range([_height - _margins.top - _margins.bottom, 0])))

            axes.selectAll('g.y-axis g.tick')
                .append('line')
                    .classed('grid-line', true)
                    .attr('x1', 0)
                    .attr('y1', 0)
                    .attr('x2', _width - _margins.left - _margins.right)
                    .attr('y2', 0)
        }

        function renderBody() {
            if (!_body) {
                _body = _svg.append('g')
                  .classed('body', true)
                  .attr('transform', `translate(${_margins.left}, ${_margins.top})`)
            }

            const stack = d3.stack()
                .keys(['value1', 'value2', 'value3'])
                .offset(d3.stackOffsetNone)

            const series = stack(_data)

            renderLines(series)
            renderAreas(series)
        }

        function renderLines(series) {
            const line = d3.line()
                .x((d, i) => _x(i))
                .y(d => _y(d[1]))

            const linePaths = _body.selectAll('path.line')
                .data(series)

            linePaths.enter()
                .append('path')
                .merge(linePaths)
                    .classed('line', true)
                    .style('stroke', (d, i) => _colors(i))
                    .transition()
                        .attr('d', d => line(d))

        }

        function renderAreas(series) {
            const area = d3.area()
              .x((d, i) => _x(i))
              .y0(d => _y(d[0]))
              .y1(d => _y(d[1]))

            const areaPaths = _body.selectAll('path.area')
                .data(series)

            areaPaths.enter()
                .append('path')
                .merge(areaPaths)
                    .classed('area', true)
                    .style('fill', (d, i) => _colors(i))
                .transition()
              .attr('d', d => area(d))
        }

        _chart.x = function (x) {
            if (!arguments.length) return _x
            _x = x
            return _chart
        }

        _chart.y = function (y) {
            if (!arguments.length) return _y
            _y = y
            return _chart
        }

        _chart.data = function (data) {
            if (!arguments.length) return _data
            _data = data
            return _chart
        }

        return _chart
    }

    const numberOfDataPoint = 51

    let data = d3.range(numberOfDataPoint).map(i => {
        return {
            value1: Math.random() * 10,
            value2: Math.random() * 10,
            value3: Math.random() * 10
        }
    })

    const chart = stackedAreaChart()
      .x(d3.scaleLinear().domain([0, 50]))
      .y(d3.scaleLinear().domain([0, 30]))

    function update() {
      data = d3.range(numberOfDataPoint).map(i => {
        return {
          value1: Math.random() * 10,
          value2: Math.random() * 10,
          value3: Math.random() * 10
        }
      })

      chart.data(data).render()
    }

    update()
</script>
<div class="control-group">
    <button onclick="update()">Update</button>
</div>
</body>
</html>
複製程式碼

效果如下:

d3.js 入門學習記錄(九) 用佈局實現餅圖 堆疊面積圖 矩陣樹圖 思維樹圖 封閉圖

需要注意的是我們在設定 line 和 area 要指定正確的 x,y 取值。

 const line = d3.line()
    .x((d, i) => _x(i))
    .y(d => _y(d[1]))

 const area = d3.area()
    .x((d, i) => _x(i))
    .y0(d => _y(d[0]))
    .y1(d => _y(d[1]))
複製程式碼

矩陣樹圖

d3.treemap() 可以幫我們構造矩陣樹圖佈局。

它為資料項附加以下屬性:

  1. node.x0 - 矩形的左邊緣
  2. node.y0 - 矩形的上邊緣
  3. node.x1 - 矩形的右邊緣
  4. node.y1 - 矩形的下邊緣

相關配置項如下:

  1. treemap.tile() - 設定矩陣樹圖佈局的填鋪方法,預設為黃金分割填充,一般不改動就好。
  2. treemap.size() - 設定佈局尺寸寬高,引數為陣列形式。
  3. treemap.round() - 設定輸出座標是否取整。
  4. treemap.padding() - 設定塊之間的間隔。

另外 treemap 處理的資料必須為 hierarchy 處理過的。


d3.hierarchy() 會為樹狀資料的節點新增以下屬性項:

  1. node.data - 原資料
  2. node.depth - 當前節點的深度, 根節點為 0
  3. node.height - 當前節點的高度, 葉節點為 0.
  4. node.parent - 當前節點的父節點, 根節點為 null
  5. node.children - 當前節點的孩子節點(如果有的話); 葉節點為 undefined
  6. node.value - 當前節點以及 descendants(後代節點) 的總計值; 可以通過 node.sum 和 node.count 呼叫計算得來

相關的配置項如下:

  1. node.sum() - 呼叫指定的函式規則為節點附加 value 值。
  2. node.sort() - 呼叫指定的排序函式規則排序所有的後代兄弟節點。
  3. node.count() - 以葉節點的個數附加為 value 值。
  4. node.each() - 以指定函式廣度優先遍歷當前子樹.
  5. node.eachAfter() - 以指定函式後續遍歷當前子樹.
  6. node.eachBefore() - 以指定函式前序遍歷當前子樹.

相關的獲取項如下:

  1. node.ancestors() - 從當前節點開始返回其祖先節點陣列.
  2. node.descendants() - 從當前節點開始返回其後代節點陣列.
  3. node.leaves() - 返回當前節點為根節點的子樹的葉節點.
  4. node.path() - 返回從當前節點到指定目標節點的最短路徑.
  5. node.links() - 返回當前節點所在子樹的所有邊.
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
<script src="../d3.js"></script>
<script>
    function treeMapChart() {
        const _chart = {}

        let _width = 1600,
            _height = 800,
            _colors = d3.scaleOrdinal(d3.schemeCategory10),
            _nodes,
            _treemap,
            _valueAccessor,
            _svg,
            _body

        _chart.render = function () {
            if (!_svg) {
                _svg = d3.select('body').append('svg')
                  .attr('width', _width)
                  .attr('height', _height)
            }
            renderBody()
        }

        function renderBody() {
            if (!_body) {
                _body = _svg.append('g')
                    .classed('body', true)

                _treemap = d3.treemap()
                    .size([_width, _height])
                    .round(true)
                    .padding(1)
            }



            const root = d3.hierarchy(_nodes)
              .sum(_valueAccessor)
              .sort((a, b) => (b.value - a.value))

            _treemap(root)

            const cells = _body.selectAll('g.cell')
                .data(root.leaves(), d => d.data.name)

            renderCells(cells)
        }

        function renderCells(cells) {
            const cellsEnter = cells.enter()
            .append('g')
            .merge(cells)
                .classed('cell', true)
                .attr('transform', d => {
                  return `translate(${d.x0}, ${d.y0})`
                })

            cellsEnter.append('rect')

            cellsEnter
                .merge(cells)
                .select('rect')
                .transition()
                .attr('width', d => d.x1 - d.x0)
                .attr('height', d => d.y1 - d.y0)
                .style('fill', d => _colors(d.parent.data.name))


            cellsEnter.append('text')

            cellsEnter.merge(cells)
              .select('text')
              .style('font-size', 11)
              .attr('x', d =>  (d.x1 - d.x0) / 2)
              .attr('y', d =>  (d.y1 - d.y0) / 2)
              .attr('text-anchor', 'middle')
              .text(d => d.data.name)
              .style('opacity', function (d) {
                return this.getComputedTextLength() < (d.x1 - d.x0) ? 1 : 0
                })

            cells.exit().remove()
        }


        _chart.nodes = function (n) {
            if (!arguments.length) return _nodes;
            _nodes = n;
            return _chart;
        };
        _chart.valueAccessor = function (fn) {
            if (!arguments.length) return _valueAccessor;
            _valueAccessor = fn;
            return _chart;
        };


        return _chart
    }

    const chart = treeMapChart();

    function flare() {
        d3.json("treeData.json").then(nodes => {
            chart.nodes(nodes).valueAccessor(size).render();
        })
    }

    function size(d) {
      return d.size;
    }

    function count() {
      return 1;
    }

    function flip(chart) {
      chart.valueAccessor(chart.valueAccessor() === size ? count : size).render();
    }
</script>
<div class="control-group">
    <button onclick="flare()">Render Flare</button>
    <button onclick="flip(chart)">Flip Value vs. Count</button>
</div>
</body>
</html>
複製程式碼

treeData.json:

{
  "name": "flare",
  "children": [
    {
      "name": "analytics",
      "children": [
        {
          "name": "cluster",
          "children": [
            {"name": "AgglomerativeCluster", "size": 3938},
            {"name": "CommunityStructure", "size": 3812},
            {"name": "HierarchicalCluster", "size": 6714},
            {"name": "MergeEdge", "size": 743}
          ]
        },
        {
          "name": "graph",
          "children": [
            {"name": "BetweennessCentrality", "size": 3534},
            {"name": "LinkDistance", "size": 5731},
            {"name": "MaxFlowMinCut", "size": 7840},
            {"name": "ShortestPaths", "size": 5914},
            {"name": "SpanningTree", "size": 3416}
          ]
        },
        {
          "name": "optimization",
          "children": [
            {"name": "AspectRatioBanker", "size": 7074}
          ]
        }
      ]
    },
    {
      "name": "animate",
      "children": [
        {"name": "Easing", "size": 17010},
        {"name": "FunctionSequence", "size": 5842},
        {
          "name": "interpolate",
          "children": [
            {"name": "ArrayInterpolator", "size": 1983},
            {"name": "ColorInterpolator", "size": 2047},
            {"name": "DateInterpolator", "size": 1375},
            {"name": "Interpolator", "size": 8746},
            {"name": "MatrixInterpolator", "size": 2202},
            {"name": "NumberInterpolator", "size": 1382},
            {"name": "ObjectInterpolator", "size": 1629},
            {"name": "PointInterpolator", "size": 1675},
            {"name": "RectangleInterpolator", "size": 2042}
          ]
        },
        {"name": "ISchedulable", "size": 1041},
        {"name": "Parallel", "size": 5176},
        {"name": "Pause", "size": 449},
        {"name": "Scheduler", "size": 5593},
        {"name": "Sequence", "size": 5534},
        {"name": "Transition", "size": 9201},
        {"name": "Transitioner", "size": 19975},
        {"name": "TransitionEvent", "size": 1116},
        {"name": "Tween", "size": 6006}
      ]
    },
    {
      "name": "data",
      "children": [
        {
          "name": "converters",
          "children": [
            {"name": "Converters", "size": 721},
            {"name": "DelimitedTextConverter", "size": 4294},
            {"name": "GraphMLConverter", "size": 9800},
            {"name": "IDataConverter", "size": 1314},
            {"name": "JSONConverter", "size": 2220}
          ]
        },
        {"name": "DataField", "size": 1759},
        {"name": "DataSchema", "size": 2165},
        {"name": "DataSet", "size": 586},
        {"name": "DataSource", "size": 3331},
        {"name": "DataTable", "size": 772},
        {"name": "DataUtil", "size": 3322}
      ]
    },
    {
      "name": "display",
      "children": [
        {"name": "DirtySprite", "size": 8833},
        {"name": "LineSprite", "size": 1732},
        {"name": "RectSprite", "size": 3623},
        {"name": "TextSprite", "size": 10066}
      ]
    },
    {
      "name": "flex",
      "children": [
        {"name": "FlareVis", "size": 4116}
      ]
    },
    {
      "name": "physics",
      "children": [
        {"name": "DragForce", "size": 1082},
        {"name": "GravityForce", "size": 1336},
        {"name": "IForce", "size": 319},
        {"name": "NBodyForce", "size": 10498},
        {"name": "Particle", "size": 2822},
        {"name": "Simulation", "size": 9983},
        {"name": "Spring", "size": 2213},
        {"name": "SpringForce", "size": 1681}
      ]
    },
    {
      "name": "query",
      "children": [
        {"name": "AggregateExpression", "size": 1616},
        {"name": "And", "size": 1027},
        {"name": "Arithmetic", "size": 3891},
        {"name": "Average", "size": 891},
        {"name": "BinaryExpression", "size": 2893},
        {"name": "Comparison", "size": 5103},
        {"name": "CompositeExpression", "size": 3677},
        {"name": "Count", "size": 781},
        {"name": "DateUtil", "size": 4141},
        {"name": "Distinct", "size": 933},
        {"name": "Expression", "size": 5130},
        {"name": "ExpressionIterator", "size": 3617},
        {"name": "Fn", "size": 3240},
        {"name": "If", "size": 2732},
        {"name": "IsA", "size": 2039},
        {"name": "Literal", "size": 1214},
        {"name": "Match", "size": 3748},
        {"name": "Maximum", "size": 843},
        {
          "name": "methods",
          "children": [
            {"name": "add", "size": 593},
            {"name": "and", "size": 330},
            {"name": "average", "size": 287},
            {"name": "count", "size": 277},
            {"name": "distinct", "size": 292},
            {"name": "div", "size": 595},
            {"name": "eq", "size": 594},
            {"name": "fn", "size": 460},
            {"name": "gt", "size": 603},
            {"name": "gte", "size": 625},
            {"name": "iff", "size": 748},
            {"name": "isa", "size": 461},
            {"name": "lt", "size": 597},
            {"name": "lte", "size": 619},
            {"name": "max", "size": 283},
            {"name": "min", "size": 283},
            {"name": "mod", "size": 591},
            {"name": "mul", "size": 603},
            {"name": "neq", "size": 599},
            {"name": "not", "size": 386},
            {"name": "or", "size": 323},
            {"name": "orderby", "size": 307},
            {"name": "range", "size": 772},
            {"name": "select", "size": 296},
            {"name": "stddev", "size": 363},
            {"name": "sub", "size": 600},
            {"name": "sum", "size": 280},
            {"name": "update", "size": 307},
            {"name": "variance", "size": 335},
            {"name": "where", "size": 299},
            {"name": "xor", "size": 354},
            {"name": "_", "size": 264}
          ]
        },
        {"name": "Minimum", "size": 843},
        {"name": "Not", "size": 1554},
        {"name": "Or", "size": 970},
        {"name": "Query", "size": 13896},
        {"name": "Range", "size": 1594},
        {"name": "StringUtil", "size": 4130},
        {"name": "Sum", "size": 791},
        {"name": "Variable", "size": 1124},
        {"name": "Variance", "size": 1876},
        {"name": "Xor", "size": 1101}
      ]
    },
    {
      "name": "scale",
      "children": [
        {"name": "IScaleMap", "size": 2105},
        {"name": "LinearScale", "size": 1316},
        {"name": "LogScale", "size": 3151},
        {"name": "OrdinalScale", "size": 3770},
        {"name": "QuantileScale", "size": 2435},
        {"name": "QuantitativeScale", "size": 4839},
        {"name": "RootScale", "size": 1756},
        {"name": "Scale", "size": 4268},
        {"name": "ScaleType", "size": 1821},
        {"name": "TimeScale", "size": 5833}
      ]
    },
    {
      "name": "util",
      "children": [
        {"name": "Arrays", "size": 8258},
        {"name": "Colors", "size": 10001},
        {"name": "Dates", "size": 8217},
        {"name": "Displays", "size": 12555},
        {"name": "Filter", "size": 2324},
        {"name": "Geometry", "size": 10993},
        {
          "name": "heap",
          "children": [
            {"name": "FibonacciHeap", "size": 9354},
            {"name": "HeapNode", "size": 1233}
          ]
        },
        {"name": "IEvaluable", "size": 335},
        {"name": "IPredicate", "size": 383},
        {"name": "IValueProxy", "size": 874},
        {
          "name": "math",
          "children": [
            {"name": "DenseMatrix", "size": 3165},
            {"name": "IMatrix", "size": 2815},
            {"name": "SparseMatrix", "size": 3366}
          ]
        },
        {"name": "Maths", "size": 17705},
        {"name": "Orientation", "size": 1486},
        {
          "name": "palette",
          "children": [
            {"name": "ColorPalette", "size": 6367},
            {"name": "Palette", "size": 1229},
            {"name": "ShapePalette", "size": 2059},
            {"name": "SizePalette", "size": 2291}
          ]
        },
        {"name": "Property", "size": 5559},
        {"name": "Shapes", "size": 19118},
        {"name": "Sort", "size": 6887},
        {"name": "Stats", "size": 6557},
        {"name": "Strings", "size": 22026}
      ]
    },
    {
      "name": "vis",
      "children": [
        {
          "name": "axis",
          "children": [
            {"name": "Axes", "size": 1302},
            {"name": "Axis", "size": 24593},
            {"name": "AxisGridLine", "size": 652},
            {"name": "AxisLabel", "size": 636},
            {"name": "CartesianAxes", "size": 6703}
          ]
        },
        {
          "name": "controls",
          "children": [
            {"name": "AnchorControl", "size": 2138},
            {"name": "ClickControl", "size": 3824},
            {"name": "Control", "size": 1353},
            {"name": "ControlList", "size": 4665},
            {"name": "DragControl", "size": 2649},
            {"name": "ExpandControl", "size": 2832},
            {"name": "HoverControl", "size": 4896},
            {"name": "IControl", "size": 763},
            {"name": "PanZoomControl", "size": 5222},
            {"name": "SelectionControl", "size": 7862},
            {"name": "TooltipControl", "size": 8435}
          ]
        },
        {
          "name": "data",
          "children": [
            {"name": "Data", "size": 20544},
            {"name": "DataList", "size": 19788},
            {"name": "DataSprite", "size": 10349},
            {"name": "EdgeSprite", "size": 3301},
            {"name": "NodeSprite", "size": 19382},
            {
              "name": "render",
              "children": [
                {"name": "ArrowType", "size": 698},
                {"name": "EdgeRenderer", "size": 5569},
                {"name": "IRenderer", "size": 353},
                {"name": "ShapeRenderer", "size": 2247}
              ]
            },
            {"name": "ScaleBinding", "size": 11275},
            {"name": "Tree", "size": 7147},
            {"name": "TreeBuilder", "size": 9930}
          ]
        },
        {
          "name": "events",
          "children": [
            {"name": "DataEvent", "size": 2313},
            {"name": "SelectionEvent", "size": 1880},
            {"name": "TooltipEvent", "size": 1701},
            {"name": "VisualizationEvent", "size": 1117}
          ]
        },
        {
          "name": "legend",
          "children": [
            {"name": "Legend", "size": 20859},
            {"name": "LegendItem", "size": 4614},
            {"name": "LegendRange", "size": 10530}
          ]
        },
        {
          "name": "operator",
          "children": [
            {
              "name": "distortion",
              "children": [
                {"name": "BifocalDistortion", "size": 4461},
                {"name": "Distortion", "size": 6314},
                {"name": "FisheyeDistortion", "size": 3444}
              ]
            },
            {
              "name": "encoder",
              "children": [
                {"name": "ColorEncoder", "size": 3179},
                {"name": "Encoder", "size": 4060},
                {"name": "PropertyEncoder", "size": 4138},
                {"name": "ShapeEncoder", "size": 1690},
                {"name": "SizeEncoder", "size": 1830}
              ]
            },
            {
              "name": "filter",
              "children": [
                {"name": "FisheyeTreeFilter", "size": 5219},
                {"name": "GraphDistanceFilter", "size": 3165},
                {"name": "VisibilityFilter", "size": 3509}
              ]
            },
            {"name": "IOperator", "size": 1286},
            {
              "name": "label",
              "children": [
                {"name": "Labeler", "size": 9956},
                {"name": "RadialLabeler", "size": 3899},
                {"name": "StackedAreaLabeler", "size": 3202}
              ]
            },
            {
              "name": "layout",
              "children": [
                {"name": "AxisLayout", "size": 6725},
                {"name": "BundledEdgeRouter", "size": 3727},
                {"name": "CircleLayout", "size": 9317},
                {"name": "CirclePackingLayout", "size": 12003},
                {"name": "DendrogramLayout", "size": 4853},
                {"name": "ForceDirectedLayout", "size": 8411},
                {"name": "IcicleTreeLayout", "size": 4864},
                {"name": "IndentedTreeLayout", "size": 3174},
                {"name": "Layout", "size": 7881},
                {"name": "NodeLinkTreeLayout", "size": 12870},
                {"name": "PieLayout", "size": 2728},
                {"name": "RadialTreeLayout", "size": 12348},
                {"name": "RandomLayout", "size": 870},
                {"name": "StackedAreaLayout", "size": 9121},
                {"name": "TreeMapLayout", "size": 9191}
              ]
            },
            {"name": "Operator", "size": 2490},
            {"name": "OperatorList", "size": 5248},
            {"name": "OperatorSequence", "size": 4190},
            {"name": "OperatorSwitch", "size": 2581},
            {"name": "SortOperator", "size": 2023}
          ]
        },
        {"name": "Visualization", "size": 16540}
      ]
    }
  ]
}
複製程式碼

效果如下:

以size排序:

d3.js 入門學習記錄(九) 用佈局實現餅圖 堆疊面積圖 矩陣樹圖 思維樹圖 封閉圖

以子節點數目排序:

d3.js 入門學習記錄(九) 用佈局實現餅圖 堆疊面積圖 矩陣樹圖 思維樹圖 封閉圖

我們使用下面的程式碼完成了對 json 資料的處理

_treemap = d3.treemap()
    .size([_width, _height])
    .round(true)
    .padding(1)

const root = d3.hierarchy(_nodes)
    .sum(_valueAccessor)
    .sort((a, b) => (b.value - a.value))

_treemap(root)
複製程式碼

應為樹圖只渲染葉節點,所以我們在傳遞資料時傳遞的是 root.leaves()

然後就是常見的對資料進行渲染,我們對 text 多加了個超出就塊寬度就隱藏的功能。

思維樹圖

d3.tree() 幫我們對 hierarchy 資料完成樹的佈局初始化。

它為節點新增以下屬性:

  1. node.x - 節點的 x 座標
  2. node.y - 節點的 y 座標

配置項:

  1. tree.size() - 以陣列的形式設定樹圖寬高。
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        .node circle {
            cursor: pointer;
            fill: #fff;
            stroke: steelblue;
            stroke-width: 1.5px;
        }
        path.link {
            fill: none;
            stroke: #ccc;
            stroke-width: 1.5px;
        }
    </style>
</head>
<body>
<script src="../d3.js"></script>
<script>
    function treeChart() {
        const _chart = {}

        let _width = 1700,
            _height = 1700,
            _margins = {top: 30, right: 200, bottom: 30, left: 60},
            _duration = 300,
            _i = 0,
            _nodes,
            _root,
            _svg,
            _body

        _chart.render = function () {
            if (!_svg) {
                _svg = d3.select('body')
                    .append('svg')
                        .attr('width', _width)
                        .attr('height', _height)
            }
            renderBody()
        }

        function renderBody() {
            if (!_body) {
                _body = _svg.append('g')
                    .classed('body', true)
                    .attr('transform', `translate(${_margins.left}, ${_margins.top})`)
            }

            _root = d3.hierarchy(_nodes)

            render(_root)
        }

        function render(root, source) {
            const tree = d3.tree()
                .size([_width - _margins.left - _margins.right, _height - _margins.top - _margins.bottom])

            tree(root)

            renderNodes(root, source)

            renderLinks(root)
        }

        function toggle(d) {
            if (d.children) {
                d._children = d.children
                d.children = null
            } else {
                d.children = d._children
                d._children = null
            }
        }

        function renderNodes(root, source) {

            const nodeG = _body.selectAll('g.node')
              .data(root.descendants(), d => {
                    return d.id || (d.id = _i++)
              })

            const nodeEnter = nodeG.enter()
                .append('g')
                    .classed('node', true)
                    .attr('transform', d => `translate(${source ? source.y : d.y}, ${source ? source.x : d.x})`)
                .on('click', d => {
                    toggle(d)
                    render(_root, d)
                })

            nodeEnter.append('circle')
                .attr('r', 4.5)
                .style('stroke', '#000')
                .style('fill', '#fff')


            nodeEnter.append('text')
                .attr('x', d => {
                    return d.children || d._children ? -10 : 10
                })
                .attr('dy', '.35em')
                .attr('text-anchor', d => {
                    return d.children || d._children ? 'end' : 'start'
                })
                .text(d => d.data.name)
            .transition().duration(_duration)
                .attr('font-size', '11')


            const nodeUpdate = nodeEnter.merge(nodeG)
                .transition().duration(_duration)
                .attr('transform', d => `translate(${d.y}, ${d.x})`)

            nodeUpdate.select('circle')
                .style('fill', d => {
                    return d._children ? 'lightsteelblue' : '#fff'
                })

            nodeUpdate.select('text')
                .style('fill-opacity', 1)

            const nodeExit = nodeG.exit()
                .transition().duration(_duration)
                    .attr('transform', d => `translate(${source ? source.y : d.y}, ${source ? source.x : d.x})`)
                    .remove()

            nodeExit.select('circle')
                .attr('r', 1e-6)
                .remove()

            nodeExit.select('text')
                .style('fill-opacity', 1e-6)
        }

        function renderLinks(root) {
            const link = _body.selectAll('path.link')
              .data(root.descendants().slice(1), d => {
                return d.id || (d.id = _i++)
              })

            link.enter()
                .insert('path', 'g')
                    .classed('link', true)
                .attr('stroke-opacity', 0)
                .merge(link)
                .transition().duration(_duration)
                    .attr('d', d => generateLinkPath(d, d.parent))
                .attr('stroke-opacity', 1)

            link.exit()
              .transition().duration(_duration)
                .attr('stroke-opacity', 0)
              .remove()
        }

        function generateLinkPath(target, source) {
            const path = d3.path()
            path.moveTo(source.y, source.x)
            path.bezierCurveTo((source.y + target.y) / 2, source.x, (source.y + target.y) / 2, target.x, target.y, target.x)
            return path.toString()
        }

        _chart.nodes = function (nodes) {
            if (!arguments.length) return _nodes
            _nodes = nodes
            return _chart
        }

        return _chart
    }

    const chart = treeChart()

    d3.json('./treeData.json').then(nodes => {
        chart.nodes(nodes).render()
    })
</script>
</body>
</html>
複製程式碼

效果如下:

d3.js 入門學習記錄(九) 用佈局實現餅圖 堆疊面積圖 矩陣樹圖 思維樹圖 封閉圖

注意裡面我們將 x y 對調以將樹圖變為橫向,另外我們通過 toggle 函式將資料儲存在dom上實現了子節點的收縮。

封閉圖

封閉圖要使用 d3.pack()。

它為節點附加以下屬性:

  1. node.x - 節點中心的 x- 座標
  2. node.y - 節點中心的 y- 座標
  3. node.r - 圓的半徑

有以下配置方法:

  1. pack.radius() - 設定半徑訪問器.
  2. pack.size() - 設定佈局尺寸.
  3. pack.padding() - 設定間隙.
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        circle {
            fill: #ccc;
            stroke: #999;
            pointer-events: all;
        }
        circle.parent {
            fill: steelblue;
            fill-opacity: .1;
            stroke: steelblue;
        }
        circle.parent:hover {
            stroke-width: .5px;
        }
        circle.child {
            pointer-events: none;
        }
        text {
            font-size: 11px;
            pointer-events: none;
            fill: steelblue;
        }

    </style>
</head>
<body>
<script src="../d3.js"></script>
<script>
    function packChart() {
        const _chart = {}

        let _width = 1280,
            _height = 800,
            _nodes,
            _root,
            _valueAccessor,
            _svg,
            _body

        _chart.render = function () {
            if (!_svg) {
                _svg = d3.select('body')
                    .append('svg')
                        .attr('width', _width)
                        .attr('height', _height)
            }
            renderBody()
        }

        function renderBody() {
            if (!_body) {
                _body = _svg.append('g')
                    .classed('body', true)
            }

            const pack = d3.pack()
                .size([_width, _height])

            _root = d3.hierarchy(_nodes)
                .sum(_valueAccessor)
                .sort((a, b) => b.value - a.value)

            pack(_root)

            console.log(_root)

            renderCircles(_root.descendants())

            renderLabels(_root.descendants())
        }

        function renderCircles(nodes) {
            const circles = _body.selectAll('circle')
                .data(nodes)

            circles.enter()
                .append('circle')
                .merge(circles)
                .transition()
                    .attr('class', d => d.children ? 'parent' : 'child')
                    .attr('cx', d => d.x)
                    .attr('cy', d => d.y)
                    .attr('r', d => d.r)

            circles.exit()
                .transition()
                    .attr('r', 0)
                .remove()
        }

        function renderLabels(nodes) {
            const labels = _body.selectAll('text')
              .data(nodes)

            labels.enter()
              .append('text')
              .attr('dy', '.35rem')
              .attr('text-anchor', 'middle')
              .merge(labels)
              .filter(d => d.children)
              .attr('x', d => d.x)
              .attr('y', d => d.y)
              .text(d => d.data.name)

            labels.exit().remove()
        }

        _chart.nodes = function (nodes) {
            if (!arguments.length) return _nodes
            _nodes = nodes
            return _chart
        }

        _chart.valueAccessor = function (fn) {
            if (!arguments.length) return _valueAccessor
            _valueAccessor = fn
            return _chart
        }

        return _chart
    }

    const chart = packChart()

    function flare() {
      d3.json('./treeData.json').then(nodes => {
        chart.nodes(nodes).valueAccessor(size).render()
      })
    }

    function size(d) {
        return d.size
    }

    function count() {
        return 1
    }

    function flip() {
        chart.valueAccessor(chart.valueAccessor() === size ? count : size).render()
    }
</script>
<div class="control-group">
    <button onclick="flare()">Render Flare</button>
    <button onclick="flip()">Flip Value vs. Count</button>
</div>
</body>
</html>
複製程式碼

效果如下:

d3.js 入門學習記錄(九) 用佈局實現餅圖 堆疊面積圖 矩陣樹圖 思維樹圖 封閉圖

相關文章