Tutorial: Introduction to D3

Following Jan Willem Tulp's Tutorials on D3

by gene

HTML

<script src="https://github.com/mbostock/d3/raw/v1.10.1/d3.js"></script>

JavaScript

function DataItem(r) {
    var self = this;
    this.active = false;
    this.color = function() { return self.active ? 'red' : 'blue' }
    this.radius = r;
    this.x = Math.random();
    this.y = Math.random();
}

// Generate some random data
var data = [];
for (i = 2; i < 5; i++) {
    data.push(DataItem(Math.log(i) / 10);
}

function ViewA() {    
    this.render = function(items) {
        items
            .style('fill', function(d) { return d.color(); })
            .style('r', function(d) { return d.radius; } );
    }
}
    
function ViewB() {
    this.render = function(items) {
        items
            .style('fill', function(d) { return 'orange'; })
            .style('r', function(d) { return 1.5*d.radius; } );
    }
}



// Then add the SVG canvas to the body of the page 
var h = 500;
var w = 800;
var vis = d3.select("body")           // jQuery-like selector
    .append("svg:svg")                // add the svg:svg element
    .attr("width", w)    // and set width and height
    .attr("height", h);               // of the appended svg element


var x = d3.scale.linear()
    .domain([0,1])
    .range([w / 2 - 400, w / 2 + 400]);

var y = d3.scale.linear()
    .domain([0,1])
    .range([0, h]);

var r = d3.scale.linear()
    .domain([0,1])
    .range([5,10]);

var c = d3.scale.linear()
    .domain([0,1])
    .range(["hsl(250, 50%, 50%)", "hsl(350, 100%, 50%)"])
    .interpolate(d3.interpolateHsl);


// Collection of circles.
// This collection starts empty, but is bound to the data array.
// `enter().append()` states that a new svg:circle element must be added for each new element of the data array.
var view = new ViewA();
vis.selectAll("circle")
    .data(data)
    .enter().append("svg:circle")
    .attr("cx", function () { return x(Math.random()); })
    .attr("cy", function () { return y(Math.random()); })
    .call(view.render)
    .on("mouseover", function() {
        d3.select(this).transition()
            .attr("cy", function () { return...