Moreal D3.js Wiki

作者: 雷朝建 | 来源:发表于2018-04-21 17:27 被阅读0次

    导读

    此文乃<Moreal D3.js Wiki>的学习笔记(https://kb.moreal.co/d3/), 简略看了一下感觉甚好. 以下这段话摘自此网站:
    What is this document and who is it intended for?
    Since Mike Bostock, creator of the D3 library, shared the excellent D3.js library with all of us, we thought we should give something back in return to the community. Although this document has been initially created for internal use, we felt that sharing it might help some people struggling to get the grasp of the basics (and even some more advanced features) of the vast D3.js library. There might be more efficient ways to handle specific functions, but while we gain more experience, this document will keep evolving with us. Enjoy!

    D3 Basic Usage

    D3采用链式写法, select/selectAll选择元素, enter新增元素:

        const dataset = [4, 8, 7, 42, 3];
    
        d3.select('.chart').append('div')
          .selectAll('div')
          .data(dataset)
          .enter().append('div')
          .attr('class', 'd3box')
          .text(d => d);
    
    • 通过append新增一个div.
    • 在selectAll虚拟创建N个div(N由data决定)
    • 通过data函数, 将数据源绑定到dom元素上, 通过enter().append的操作, 将之前虚拟创建的div按照数组顺序, 一一创建出来.
    • 给创建出来的每个div, 赋值class和text.


      image.png

      这里实际上涉及到d3中重要的三个函数:

    • enter: 提供数据, dom中不存在匹配的元素, 新增.
    • update: 提供数据, dom中存在匹配的元素, 更新.
    • exit: 提供元素, 没有匹配的数据, 删除.
        d3.selectAll('.d3box').data([32, 12])
          .text(d => d)
          .exit().remove();
    

    这时候, 非[32, 12]的dom元素将会被删除.

        d3.selectAll('.d3box').data([32, 12, 32, 45, 67, 31, 34, 2])
          .enter().append('div')
          .attr('class', 'd3box')
          .text(d => d);
    

    这时候, 多余出来的数据, 将被更新到dom上.

    Chart Dimensions

    我们在绘图时候, 最好要增加绘图区域的margin(外间距). 主要原因有两个: 1. 为了美观. 2. 如果存在坐标轴, 则正好存在空间绘制.
    所以一般代码都会这么写:

        const width = 960;
        const height = 500;
        const margin = {top: 20, right: 20, bottom: 20, left: 20};
    
        d3.select('svg')
          .attrs({
            width: width + margin.left + margin.right,
            height: height + margin.top + margin.bottom
          });
    

    Labels

    一个绘图, 通常会由label说明:

        const xaxisLabel = svg.append('text')
          .attrs({
            class: 'd3-chart-label label-x-axis',
            x: width / 2,
            y: height + (margin.bottom / 2),
            dy: '1em',
            'text-anchor': 'end'
          })
          .text('x Axis Label');
    
        const yaxisLabel = svg.append('text')
          .attrs({
            class: 'd3-chart-label label-y-axis',
            x: -height / 2,
            y: margin.left,
            dy: '1em',
            transform: 'rotate(-90)',
            'text-anchor': 'middle',
          })
          .text('y Axis Label');
    

    xaxisLabel比较好理解, 将文本水平放置在位置(width / 2, height + (margin.bottom / 2))的位置. 但是由于yaxisLabel的文字是竖向的, 所以我们可以先将文本放在(-height / 2, margin.left)上, 再逆时针旋转90度(rotate(-90))即可.

    Scales

    Scales通常用于处理domain和range的关系.

        const dataset = [
          {"name":"Nick", "level":1232},
          {"name":"George", "level":922},
          {"name":"Alekos", "level":1651},
          {"name":"Kostas", "level":201}
        ];
        const opacityScale = d3.scaleLinear()
          .domain([0, d3.max(dataset, d => d.level)])
          .range([.2, 1]);
        const colorScale = d3.scaleOrdinal()
          .domain(["Nick", "George", "Alekos", "Kostas"])
          .range(["red", "orange", "yellow", "green"]);
    

    这里通过scaleLinear将[0, 1651]线性映射到[.2, 1]上. 而通过scaleOrdinal将名字和颜色一一对应起来.

    Axes

    常用的坐标轴可分为以下几类:1. 线性坐标轴, 例如从0, 1, 2, ...,10作为x轴. 2. 时间坐标轴.

        const width = 500;
        const height = 500;
        const margin = {top: 20, right: 20, bottom: 20, left: 20};
        const points = [3, 6, 2, 7, 9, 1];
    
        const svg = d3.select('svg').attrs({
          width: width + margin.left + margin.right,
          height: height + margin.top + margin.bottom
        });
    
        const x = d3.scaleLinear().domain([0, 10]).range([margin.left, width + margin.left]);
        const y = d3.scaleLinear().domain([d3.min(points), d3.max(points)]).range([height + margin.top, margin.top]);
    
        const gx = svg.append('g').attr('transform', `translate(0,${height + margin.top})`);
        const gy = svg.append('g').attr('transform', `translate(${margin.left}, 0)`);
    
        const xAxis = d3.axisBottom(x);
        const yAxis = d3.axisLeft(y);
    
        gx.call(xAxis);
        gy.call(yAxis);
    
        svg.selectAll('circle').data(points)
          .enter().append('circle')
          .attrs({cx: (d, i) => x(i), cy: d => y(d), r: 5})
          .style('fill', 'green');
    

    这里简单实现了一个散点图, 效果如下:


    image.png

    代码简单解释如下:

    • 使用scaleLinear将x轴的[0, 10]映射到宽度[margin.left, width + margin.left]上, 将y轴的[min, max]映射到高度[height + margin.top, margin.top]上. margin的存在导致x/y轴有空间进行绘制.
    • 为x/y创建绘图空间gx/gy, 并设置位置(transform, translate)
    • 使用d3.axisBottom/axisLeft分别创建下x坐标轴和y坐标轴, 并在gx/gy中call, 生成坐标轴.
    • 绘制散点图.

    Tooltips

    任何一个绘图, 都应该存在tooltips, 最简单的实现方式是加入: title.

        svg.selectAll('circle').data(points)
          .enter().append('circle')
          .attrs({cx: (d, i) => x(i), cy: d => y(d), r: 5})
          .style('fill', 'green')
          .append('title')
          .text(String);
    

    如果需要更加智能化, 则需要手动编写mousemove/mouseout函数, 然后定义一个tooltips的div, move时候显示, out后隐藏.

    Line Chart

    一个简单的线图代码如下:

        const width = 500;
        const height = 500;
        const margin = {top: 20, right: 20, bottom: 20, left: 20};
        const dataset = [
          {
            'date': '2011-07-01T19:14:34.000Z',
            'value': 58.13
          },
          {
            'date': '2011-07-01T19:13:34.000Z',
            'value': 53.98
          },
          {
            'date': '2011-07-01T19:12:34.000Z',
            'value': 67.00
          },
          {
            'date': '2011-07-01T19:11:34.000Z',
            'value': 89.70
          },
          {
            'date': '2011-07-01T19:10:34.000Z',
            'value': 99.00
          }
        ];
    
        const parseDate = d3.timeParse('%Y-%m-%dT%H:%M:%S.%LZ');
        dataset.forEach(d => {
          d.date = parseDate(d.date);
          d.value = +d.value;
        });
    
        const svg = d3.select('svg').attrs({
          width: width + margin.left + margin.right,
          height: height + margin.top + margin.bottom
        });
        const x = d3.scaleTime().domain(d3.extent(dataset, d => d.date)).range([margin.left, margin.left + width]);
        const y = d3.scaleLinear().domain([0, 1.05 * d3.max(dataset, d => d.value)]).range([margin.top + height, margin.top]);
        const gx = svg.append('g').attr('transform', `translate(0, ${height + margin.top})`);
        const gy = svg.append('g').attr('transform', `translate(${margin.left}, 0)`);
        const xAxis = d3.axisBottom(x).ticks(5);
        const yAxis = d3.axisLeft(y).ticks(4);
        gx.call(xAxis);
        gy.call(yAxis);
    
        const line = d3.line()
          .x(d => x(d.date))
          .y(d => y(d.value));
    
        svg.append('path').data([dataset])
          .styles({
            fill: 'none',
            stroke: 'steelblue',
            'stroke-width': '2px'
          })
          .attr('d', line);
    

    效果图如下:


    image.png
    • 使用d3.timeParse将字符串时间格式化为Date类型.
    • 提供margin用于绘制坐标轴.
    • 使用d3.axisBottom/d3.axisLeft绘制底部坐标轴和坐标坐标轴. 使用ticks(N)进行间隔设置.
    • 使用path进行线条的绘制.

    Line Chart with Vertical Line

    我们要达到一个效果, 鼠标移上去后, 会有一条竖直的线:

        const focus = svg.append('g').append('line')
          .styles({ display: 'none', 'stroke-width': 2, stroke: 'black' });
        svg.on('mousemove', function () {
          const x = d3.mouse(this)[0];
          if (x >= margin.left && x <= margin.left + width) {
            focus.attrs({ x1: x, y1: height + margin.top, x2: x, y2: margin.top })
              .style('display', '');
          } else {
            focus.style('display', 'none');
          }
        }).on('mouseout', function () {
          focus.style('display', 'none');
        });
    

    原理很简单. 我们创建一个line, 然后隐藏它. 在mousemove/mouseout情况下显示/隐藏它即可.

    Line Chart with Area Fill

    如果想绘制面积图, 则需要做以下两点:

    • 填充颜色需要设置: style('fill', '#f1f1f1')
    • 使用d3.area代替d3.line, 并且需要提供x, y0, y1, 形成线条. 无数个x就形成了面积图.
        const area = d3.area()
          .x(d => x(d.date))
          .y0(y(0))
          .y1(d => y(d.value));
    
        svg.append('path').data([dataset])
          .styles({
            fill: '#f1f1f1',
            stroke: 'steelblue',
            'stroke-width': '2px'
          })
          .attr('d', area);
    

    Line Chart with Brush Zoom

    如果想得到画刷的效果, 可直接使用d3.brushX:

        svg.append('g').attr('class', 'brush')
          .call(d3.brushX().extent([[margin.left, margin.top], [width + margin.left, height + margin.top]]));
    

    相关文章

      网友评论

        本文标题:Moreal D3.js Wiki

        本文链接:https://www.haomeiwen.com/subject/jlbxlftx.html