d3(1) Basics

  • SVG: Scalable Vector Graphics
1
2
3
4
5
6
7
8
9
<!-- using an img tag -->
<img src="some.svg" alt="">

<!-- using SVG tags -->
<svg width="600" height="600">
<circle cx='150' cy='150' r='5' fill='grey'></circle>
</svg>

<!-- JavaScript -->
  • In HTML file
1
2
3
4
5
<svg width="600" height="600">
<rect x="300" y="100" fill="blue" width="100" height="200"></rect>
<circle cx="200" cy="200" r="50" fill="pink" stroke="red" stroke-width="2"></circle>
<line x1="100" y1="100" x2="120" y2="300" stroke="grey" stroke-width="3"></line>
</svg>
  • SVG Paths
1
<path d="M150 0 L75 200 L225 200 Z" fill="orange"/>
  • M - moveto. The starting point
  • L - lineto. Draw line to a certain point
  • Z - closepath
  • H/V - Horizontal/Vertical lineto
  • C - Curveto
  • S - Smooth curveto

D3 basics

  • Select an item const d = d3.select('div');

  • Select all items d3.selectAll('div');

  • Append tags to a container

    1
    2
    const svg = canvas.append('svg');
    svg.append('rect');
  • Method chainning & attributes

    1
    2
    svg.attr('height', 600);
    svg.append('rect').attr('height', 300).attr('width', 300);
  • Text element

    1
    2
    3
    4
    5
    6
    svg.append('text');
    .attr('x', 20)
    .attr('y', 200)
    .attr('fill', blue)
    .text('hello world!')
    .style('font-family', 'arial')
  • Groups

    1
    const group = svg.append('g');

Data with D3

  • Example without database

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    const data = [
    {width: 200, height: 100, fill: 'purple'}
    ];

    const svg = d3.select('svg');
    const rect = svg.select('rect')
    .data(data)
    .attr('width', (d, i, n) => d.width)
    .attr('height', d => d.height)
    .attr('fill', d => d.fill);
  • For multiple elements, data with multiple entries will apply to each element automatically

  • If the data retrieved from database has more entries than the hard-coded DOM, then

    1
    2
    3
    4
    5
    6
    const rects = d3.selectAll('rect')
    .data(data)

    rects.enter()
    .append('rect')
    .attr()
  • Data with JSON

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    const svg = d3.select('svg');
    d3.json('planets.json').then(data => {

    const circs = svg.selectAll('circle') // though there is no circle in the DOM
    .data(data); // bind the data to the invisible entries

    // add attrs to circs already in the DOM
    circs.attr('cy', 200)
    .attr('cx', d => d.distance)
    .attr('r', d => d.radius)
    .attr('fill', d => d.fill)

    // append the enter selection to the DOM
    circs.enter()
    .append('circle')
    .attr('cx', d => d.distance)
    .attr('r', d => d.radius)
    .attr('fill', d => d.fill)
    })