D3.js--从陌生到熟悉

Moreal D3.js Wiki

2018-04-21  本文已影响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);
    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

代码简单解释如下:

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

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

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

    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]]));
上一篇 下一篇

猜你喜欢

热点阅读