Intro to D3 (Data-Driven Documents)

D3

  • D3 is a javascript library for data visualization.
  • Uses HTML, CSS, SVG
  • Easy-to-use API

(This is a post of what I’ve learned from Sohaib Nahal’s D3 course)

To start using D3 in your vanilla JS/ HTML/ CSS project, you can link to the CDN in your HTML scripts.

Using D3 to do DOM manipulation is fairly straightforward: (all following code in index.js)

// selects one matching element
d3.select();
// selects all matching elements
d3.selectAll();

d3.select('hi').style('color', 'red')
.attr('class', 'heading')
.text('Updated h1 tag');

d3.select('body').append('p').text('First Paragraph')
d3.select('body').append('p').text('Second Paragraph')
d3.select('body').append('p').text('Third Paragraph')

d3.selectAll('p').style('color', 'blue')

But the fun part of D3 is data visualization, so let’s put some data in.


var dataset = [1, 2, 3, 4, 5];

d3.select('body')
    .selectAll('p')
    .data(dataset)
    .enter()
    .append('p') // appends paragraph for each data element
    .text('D3 is awesome!!');
    //.text(function(d) { return d; });

Let’s do more with the data by making it a bar chart:


var dataset = [80, 100, 56, 120, 180, 30, 40, 120, 160];

var svgWidth = 500, svgHeight = 300, barPadding = 5;
var barWidth = (svgWidth / dataset.length);


var svg = d3.select('svg')
    .attr("width", svgWidth)
    .attr("height", svgHeight);

var yScale = d3.scaleLinear()
    .domain([0, d3.max(dataset)])
    .range([0, svgHeight]);

var barChart = svg.selectAll("rect")
    .data(dataset)
    .enter()
    .append("rect")
    .attr("y", function (d) {
        return svgHeight - d
    })
    .attr("height", function (d) {
        return d;
    })
    .attr("width", barWidth - barPadding)
    .attr("transform", function (d, i) {
        var translate = [barWidth * i, 0];
        return "translate(" + translate + ")";
    });
var text = svg.selectAll("text")
    .data(dataset)
    .enter()
    .append("text")
    .text(function(d) {
        return d;
    })
    .attr("y", function(d, i) {
        return svgHeight - d - 2;
    })
    .attr("x", function(d, i) {
        return barWidth * i;
    })
    .attr("fill", "#A64C38");

Relevant resource: d3.enter() and d3.exit() under the hood

To be continued from https://scrimba.com/p/pb4WsX/c6rwbhr

Leave a comment

Design a site like this with WordPress.com
Get started