D3 Starter Kit

Concepts Demos Maps Tributaries About

Featured Example

Triangulation of Random Points.
Featured examples are simple but effective learning tools. Never too much JS, HTML, or CSS. Perfect for those learning D3.

See the Pen Delaunay Triangulation of Random Points by Adam Luikart (@adamesque) on CodePen.

Essentials

Thinking with Joins
You want one circle per datum. Instead of instructing D3 to create circles, then, tell D3 that the selection "circle" should correspond to data. This concept is called the data join ...
Mike Bostock in Thinking with Joins (https://bost.ocks.org/mike/join/)

Read it bost.ocks.org.

Selections
A selection is an array of elements pulled from the current document. D3 uses CSS3 to select elements. For example, you can select by tag ("div"), class (".awesome"), unique identifier ("#foo"), attribute ("[color=red]"), or containment ("parent child").
Mike Bostock in Selections (https://github.com/mbostock/d3/wiki/Selections)

Read it on GitHub.

Scales in D3
One more thing: to prevent your brain from mixing up the input domain and output range terminology, I’d like to propose a little exercise. When I say “input,” you say “domain.” Then I say “output,” and you say “range.” Ready?
Scott Murray in Interactive Data Visualization (http://chimera.labs.oreilly.com/books/1230000000345/ch07.html)

Interactive Data Visualization for the Web, Chapter 7.

Drawing in SVG
There are a number of visual elements that you can include between those svg tags, including rect, circle, ellipse, line, text, and path. (Sorry, zebras is not valid in this context.)
Scott Murray in Interactive Data Visualization (http://chimera.labs.oreilly.com/books/1230000000345/ch03.html)

Interactive Data Visualization for the Web, Chapter 3.

Force Directed Graph

An interactive graph with forces like "gravity", "charge", and "friction". It could be cyclic, or acyclic, directional or non-directional, connected, or disconnected. It usually all depends on the data! If a node is connected to another via one or more edges, a relationship exists among these data.

Here, we have the social media usage of fifteen departments, initiatives, and other governmental organizations of New York City. The relationship that connects one or more of them is the fact that they share a use of one or more of the same social media service.

Definitions

Force Layout
Force-directed layouts are so-called because they use simulations of physical forces to arrange elements on the screen. The elements are nodes and edges; SVG shapes and lines, respectively.
Scott Murray in Interactive Data Visualization, Chapter 11
An Ordinal Scale: Categorical Colors
Ordinal scales have a discrete domain, such as a set of names or categories. There are also quantitative scales, which have a continuous domain, such as the set of real numbers. Scales are an optional feature in D3; you don't have to use them, if you prefer to do the math yourself. However, using scales can greatly simplify the code needed to map a dimension of data to a visual representation.
Mike Bostock in (https://github.com/mbostock/d3/wiki/Ordinal-Scales)
Nodes
Each node has the following attributes:
  • index - the zero-based index of the node within the nodes array.
  • x - the x-coordinate of the current node position.
  • y - the y-coordinate of the current node position.
  • px - the x-coordinate of the previous node position.
  • py - the y-coordinate of the previous node position.
  • fixed - a boolean indicating whether node position is locked.
  • weight - the node weight; the number of associated links.
Mike Bostock in https://github.com/mbostock/d3/wiki/Force-Layout#nodes
Links
Each link has the following attributes:
  • source - the source node (an element in nodes).
  • target - the target node (an element in nodes).
Mike Bostock in https://github.com/mbostock/d3/wiki/Force-Layout#links
Range Bands
Sets the output range from the specified continuous interval. The array interval contains two elements representing the minimum and maximum numeric value. This interval is subdivided into n evenly-spaced bands, where n is the number of (unique) values in the input domain.
Mike Bostock in https://github.com/mbostock/d3/wiki/Ordinal-Scales#ordinal_rangeBands
Tick
The "tick" events are dispatched for each tick of the simulation. Listen to tick events to update the displayed positions of nodes and links. For example ...
Scott Murray in Interactive Data Visualization, Chapter 11

                                
        // Data, width and height
        //
        var dataset = null;
        var w = $('.force-ex-1').innerWidth();
        var h = 600;
        
        if ((w > 0) && (!force)) {
            
            d3.json("data/nyc-sm-usage-relationships.json", visualizeGraphData);  
        }
        
        function visualizeGraphData(error, json) {
            
            if (error) {
                return console.warn(error);
            }

            // Set our data var.
            //
            dataset = json;

            // Initialize a default force layout, using the nodes and edges in dataset.
            //
            force = d3.layout.force()
                .nodes(dataset.nodes)
                .links(dataset.edges)
                .size([w, h])
                .gravity(0.050)
                .linkDistance([200])
                .linkStrength([0.25])
                .charge([-300])
                .start();

            var colors = d3.scale.category20();

            // Create SVG element
            //
            var svg = d3.select('.force-ex-1')
                .append('svg')
                .attr('width', w)
                .attr('height', h);

            var g = svg.append('g');

            // Create edges as lines
            //
            var edges = g.selectAll('line')
                .data(dataset.edges)
                .enter()
                .append('line')
                .style('stroke', '#ccc')
                .style('stroke-width', '1.0');

            var nodes = g.selectAll('.node')
                .data(dataset.nodes)
                .enter().append('g')
                .attr('class', 'node')
                .call(force.drag);

            // Create nodes as circles
            //
            nodes.append('path')
                .attr('d', d3.svg.symbol()
                    .type(function (d) {
                        if (d.name == 'DOT') {
                            return 'triangle-up';
                        } else {
                            return 'circle';
                        }
                    })
                    .size(512))
                .style('fill', function (d, i) {
                    if (d.name == 'DOT') {
                        return colors(i);
                    } else {
                        return 'white';
                    }
                })
                .style('stroke', function (d, i) {
                    return colors(i);
                })
                .style('stroke-width', '2.0');

            // Define the legend as a set of material chips.
            //
            var chipsLegend = d3.select('.force-ex-1-chips-legend');
            var chips = chipsLegend.selectAll('div')
                        .data(dataset.nodes)
                        .enter()
                        .append('div')
                        .attr('class', 'mdl-chip')


            chips.append('div')
                        .attr('class', 'mdl-chip-img')
                        .style('background-color', function(d, i) { return colors(i); });
            chips.append('span')
                        .attr('class', 'mdl-chip-text')
                        .text(function(d) { return d.legendName; });


            // Every time the simulation "ticks", this will be called.
            //
            force.on('tick', function () {

                edges.attr("x1", function(d) { return d.source.x; })
                  .attr("y1", function(d) { return d.source.y; })
                  .attr("x2", function(d) { return d.target.x; })
                  .attr("y2", function(d) { return d.target.y; });

                nodes.attr("transform", function (d) {
                    return "translate(" + d.x + "," + d.y + ")";
                });

            });

        }                                
                            

Categorical Color Fun

So little the code, so colorful the result! First, read Thinking with Joins to understand the select().data().enter().append() method chain. It is a quick and insightful read. You may also want to check out ordinal scales that produce a range of categorical colors.

By knowing only a little about SVG, you can read the code below and understand exactly how the colored circles are being produced. That's it! This little bit of code is all that is needed.

Definitions

SVG: Drawing Circles
The circle element draws a circle. Use cx and cy to specify the coordinates of the center, and r to specify the radius
Scott Murray in Interactive Data Visualization, Chapter 3
An Ordinal Scale: Categorical Colors
Ordinal scales have a discrete domain, such as a set of names or categories. There are also quantitative scales, which have a continuous domain, such as the set of real numbers. Scales are an optional feature in D3; you don't have to use them, if you prefer to do the math yourself. However, using scales can greatly simplify the code needed to map a dimension of data to a visual representation.
Mike Bostock in (https://github.com/mbostock/d3/wiki/Ordinal-Scales)

                        
    // Width and height of containing element 
    //
    var w = $('.color-c-ex1').innerWidth();
    var h = Math.min(400, w);

    if ((w > 0) && (!circles)) {

        var svg = d3.select('.color-c-ex1')
            .append('svg')
            .attr('width', w)
            .attr('height', h);
        var n = 35;
        var m = 30;
        var data = []

        for(var i = 40; i > 0; i--){
         data.push(i); 
        }

        var c20c = d3.scale.category20c();
        var g = svg.append("g")
        .attr("transform", "translate(5,10)");

        circles = g.selectAll("circle")
        .data(data);

        circles.enter()
        .append("circle")
        .attr({
          cx: (w/2),
          cy: 205,
          r: function(d,i) {return Math.random()*d*5},
          fill: c20c
        });
    }  
                        
                    

Maps

Maps require a little more time to learn and understand than the D3 core API. The best learning resource for creating maps with D3 is Mike Bostock's Let's Make a Map tutorial.

As you code a map visualization using D3, you will encounter terms you probably haven't read about yet. Words like graticule, and scalerank require a little research at first, but with some reading, and good examples to follow you'll most likely be on your way to map visualization greatness.

See the Pen Another D3 Satellite Projection by Daniel Kemper (@dotComb) on CodePen.

Definitions

Projection
Map projections are attempts to portray the surface of the earth or a portion of the earth on a flat surface. Some distortions of conformality, distance, direction, scale, and area always result from this process. Some projections minimize distortions in some of these properties at the expense of maximizing errors in others. Some projection are attempts to only moderately distort all of these properties.
  • Conformality: When the scale of a map at any point on the map is the same in any direction, the projection is conformal. Meridians (lines of longitude) and parallels (lines of latitude) intersect at right angles. Shape is preserved locally on conformal maps.
  • Distance: A map is equidistant when it portrays distances from the center of the projection to any other place on the map.
  • Direction: A map preserves direction when azimuths (angles from a point on a line to another point) are portrayed correctly in all directions.
  • Scale: Scale is the relationship between a distance portrayed on a map and the same distance on the Earth.
  • Area: When a map portrays areas over the entire map so that all mapped areas have the same proportional relationship to the areas on the Earth that they represent, the map is an equal-area map.
Peter H. Dana in (http://www.colorado.edu/geography/gcraft/notes/mapproj/mapproj_f.html)
Geo Paths
The primary mechanism for displaying geographic data is d3.geo.path. This class is similar to d3.svg.line and the other SVG shape generators: given a geometry or feature object, it generates the path data string suitable for the "d" attribute of an SVG path element.
Mike Bostock in (https://github.com/mbostock/d3/wiki/Geo-Paths)
TopoJSON
TopoJSON is an extension of GeoJSON that encodes topology. Rather than representing geometries discretely, geometries in TopoJSON files are stitched together from shared line segments called arcs. TopoJSON eliminates redundancy, offering much more compact representations of geometry than with GeoJSON; typical TopoJSON files are 80% smaller than their GeoJSON equivalents.
Mike Bostock in https://github.com/mbostock/topojson

Learning with Tributaries and Inlets

Tributary tributary.io is a rapid prototyping and overall interactive learning tool. In addition to providing a REPL for JavaScript, one of the single greatest features of Tributary is the slider. That is; find a method parameter, an array of values, or a number that is a factor in a calculation, then click. You will notice a slider control pop up. Use it to adjust the parameter, number, or array value of your choice and see the result in real-time.

Selected Tributaries

#401 Inside the nautilus
nautilus
droplet
droplet

About

By me for you!