D3.js basics – Element selection

D3 is a superb JavaScript library for data vizualization.

Here are some basics that will get you started.

Selection of elements

You can use CSS selectors to select the elements – just like with jQuery.

d3.select()          # selects the first found element
d3.selectAll()    #selects all matching elemets

// Example
d3.selectAll('div')

Bind data

Associate element with data

d3.selectAll().('div').data([1,2,3,4,5]);

Changing styles, attributes and properties

d3.select('div').style('border', '5px black solid');
d3.select('checkbox').property('checked', 'true');
d3.select('div').attr('id', 'new');

If you don’t set a new value it returns the current value

d3.select('div').attr('class');   # returns "new"

Use classed() to add or remove a class

d3.select('div').classed('active', true);

Adding text

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

SVG

Top left corner is 0,0

<svg>
    <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>
    <g>
        <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>
    </g>
</svg>

Style SVG with CSS or D3

d3.select('svg').style('background', 'green');

Remove element

d3.select('div').remove();

Functions

.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

JavaScript Array

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

JavaScript 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;
});

You can also use ES6 JS notation:

numbers.filter((el) => {
        return el >=40;
});

var smallnumbers = someNumbers.filter( (el) {
   return el <= 40 ? this : null }
);

Anonymous function

Usage of anonymous function can provide you with data bound to that selection.

d3.select('body').selectAll('div')
.data(smallerNumbers)
.enter()
.append('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});