D3 basics

February 27, 2017 - d3, javascript

D3 is a superb JavaScript library for data vizualization.

Here are some basics that will get you started.

Selection of elements          # selects the first found element
d3.selectAll()    #selects all matching elemets

Bind data

Associate element with data


Changing styles, attributes and properties'div').style('border', '5px black solid');'checkbox').property('checked', 'true');'div').attr('id', 'new');

If you don’t set a new value it returns the current value'div').attr('class');   # returns "new"

Use classed() to add or remove a class'div').classed('active', true);

Adding text'div').style('background','lightblue').style('border', '1px darkblue solid').html('Added content');


Top left corner is 0,0

    <path d="M 10,60 40,30 50,50 60,30 70,80" style="fill:black;stroke:gray;stroke-width:4px;"></path>
    <polygon style="fill:gray;" points="80,400 120,400 160,440 120,480 60,460"></polygon>
        <circle cy="100" cx="200" r="30"></circle>
        <rect x="410" y="200" width="100" height="50" style="fill:pink;stroke:black;stroke-width:1px;"></rect>

Style SVG with CSS or d3'svg').style('background', 'green');

Remove element'div').remove();


.data() # binds each element in selection to each item in the array
.enter() # defines what to do with extra array elements
.enter().append('div')  # append a new div when there are more elements in the array than in the selection
.exit() #defines what to do when array has fewer values than selection


var numbers = [1, 2, 3, 4];
var colors = ['red', 'blue'];

Array of JSON objects

people = [
    { name: 'Peter', age: 3 },
    { name: 'Ruby', age: 2 }

Array filter

numbers.filter(function(el) {
        return el >=40
        # return el.length < 5;
var smallnumbers = someNumbers.filter(function(el) {
return el <= 40 ? this : null }

Anonymous function

Usage of anonymous function can provide you with data bound to that selection.'body').selectAll('div')
.html(function (d) {return d});

More examples of passing data
d = data value
i = index, array position

.style('background', function(d, i) {return d});
.attr('cx', function(d, i) {return i});
.html(function(d, i) {return d});
Tags: ,