Book Image

D3.js Quick Start Guide

By : Matthew Huntington
Book Image

D3.js Quick Start Guide

By: Matthew Huntington

Overview of this book

D3.js is a JavaScript library that allows you to create graphs and data visualizations in the browser with HTML, SVG, and CSS. This book will take you from the basics of D3.js, so that you can create your own interactive visualizations, to creating the most common graphs that you will encounter as a developer, scientist, statistician, or data scientist. The book begins with an overview of SVG, the basis for creating two-dimensional graphics in the browser. Once the reader has a firm understanding of SVG, we will tackle the basics of how to use D3.js to connect data to our SVG elements. We will start with a scatter plot that maps run data to circles on a graph, and expand our scatter plot to make it interactive. You will see how you can easily allow the users of your graph to create, edit, and delete run data by simply dragging and clicking the graph. Next, we will explore creating a bar graph, using external data from a mock API. After that, we will explore animations and motion with a bar graph, and use various physics-based forces to create a force-directed graph. Finally, we will look at how to use GeoJSON data to create a map.
Table of Contents (10 chapters)

Dragging an element

We want to be able to update the data for a run by dragging the associated circle. To do this, we'll use a behavior, which you can think of as a combination of multiple event handlers. For a drag behavior, there are three callbacks:

  • When the user starts to drag
  • Each time the user moves the cursor before releasing the mouse button
  • When the user releases the mouse button

There are two steps whenever we create a behavior:

  1. Create the behavior
  2. Attach the behavior to one or more elements

Put the following code at the bottom of the render() function declaration:

//put this code at the end of the render function
var drag = function(datum){
    var x = d3.event.x;
    var y = d3.event.y;
    d3.select(this).attr('cx', x);
    d3.select(this).attr('cy', y);
}
var dragBehavior = d3.drag()    
    .on('drag', drag);
d3.selectAll...