Table of Contents for
Learning D3.js 4 Mapping - Second Edition

Version ebook / Retour

Cover image for bash Cookbook, 2nd Edition Learning D3.js 4 Mapping - Second Edition by Lars Verspohl Published by Packt Publishing, 2017
  1. Learning D3.js 4 Mapping, Second Edition
  2. Title Page
  3. Second Edition
  4. Copyright
  5. Learning D3.js 4 Mapping
  6. Second Edition
  7. Credits
  8. About the Authors
  9. About the Reviewers
  10. www.PacktPub.com
  11. Why subscribe?
  12. Customer Feedback
  13. Table of Contents
  14. Preface
  15. What this book covers
  16. What you need for this book
  17. Who this book is for
  18. Conventions
  19. Reader feedback
  20. Customer support
  21. Downloading the example code
  22. Downloading the color images of this book 
  23. Errata
  24. Piracy
  25. Questions
  26. Gathering Your Cartography Toolbox
  27. Quick bootstrap
  28. Step-by-step bootstrap
  29. A lightweight web server
  30. Using the web browser as a development tool
  31. Installing the sample code
  32. Working with the developer tools
  33. Summary
  34. Creating Images from Simple Text
  35. The SVG coordinate system
  36. Line
  37. Rectangle
  38. Circle
  39. Polygon
  40. Path
  41. Experiment
  42. Paths with curves
  43. Transform
  44. Translate
  45. Scale
  46. Grouping
  47. Text
  48. Summary
  49. Producing Graphics from Data - the Foundations of D3
  50. Creating basic SVG elements
  51. The enter() function
  52. The update function
  53. The exit() function
  54. AJAX
  55. Summary
  56. Creating a Map
  57. Foundation - creating your basic map
  58. Including the dataset
  59. Experiment 1 – adjusting the bounding box
  60. Experiment 2 – creating choropleths
  61. Experiment 3 – adding click events to our visualization
  62. Experiment 4 – using updates and transitions to enhance our visualization
  63. Experiment 5 – adding points of interest
  64. Experiment 6 – adding visualizations as a point of interest
  65. Summary
  66. Click-Click Boom! Applying Interactivity to Your Map
  67. Events and how they occur
  68. Experiment 1 – hover events and tooltips
  69. Experiment 2 – tooltips with visualizations
  70. Experiment 3 – panning and zooming
  71. Experiment 4 – orthographic projections
  72. Experiment 5 – rotating orthographic projections
  73. Experiment 6 – dragging orthographic projections
  74. Summary
  75. Finding and Working with Geographic Data
  76. Geodata file types
  77. What are shapefiles and how do I get them?
  78. Acquiring shapefiles for a specific country
  79. GeoJSON
  80. A quick map in D3 with only GeoJSON
  81. TopoJSON basics
  82. TopoJSON command-line tips
  83. Preserving specific attributes
  84. Simplification
  85. Merging files
  86. Summary
  87. Testing
  88. Code organization and reusable assets
  89. Project structure
  90. Exploring the code directory
  91. Other administrative files
  92. Writing testable code
  93. Keeping methods/functions small
  94. Preventing side effects
  95. An example with viz.js
  96. Unit testing
  97. Creating resilient visualization code
  98. Adding a new test case
  99. Summary
  100. Drawing with Canvas and D3
  101. Introducing Canvas
  102. Drawing with Canvas
  103. The three drawing steps of every Canvas visual
  104. Drawing various shapes with Canvas
  105. Animating the Canvas
  106. Animating the Canvas way
  107. Getting a general overview
  108. Preparing the rain data
  109. Updating each drop
  110. Drawing frame by frame
  111. Canvas and D3
  112. Getting an overview of our experiment
  113. The data
  114. Updating each drop
  115. Binding the data
  116. Drawing the data
  117. Running the app
  118. Summary
  119. Mapping with Canvas and D3
  120. Choosing Canvas or SVG
  121. Reasons to choose SVG
  122. Reasons to choose Canvas
  123. Visualizing flight paths with Canvas and D3
  124. The data
  125. Building the flight path map in SVG
  126. Measuring the performance
  127. Building the flight path map in Canvas
  128. Setting up the map
  129. Drawing the map and listening for user input
  130. Preparing and drawing with Canvas
  131. Drawing the background scene
  132. Defining the planes
  133. Calculating the plane's positions
  134. Animating the plane
  135. Measuring the performance
  136. Optimizing performance
  137. Continuing with measuring performance
  138. Summary
  139. Adding Interactivity to Your Canvas Map
  140. Why Canvas interaction is different
  141. Drawing the world on a Canvas
  142. Setting up
  143. Drawing the world
  144. Making the world move
  145. Setting up the behavior
  146. Handling zoom and rotation
  147. Finding the Canvas object under the mouse - Picking
  148. Picking, the theory
  149. Creating all things hidden
  150. Drawing the hidden Canvas
  151. Picking the values
  152. Storing more data and using a lookup array
  153. Highlighting the country on mouse over
  154. Visualizing data per country and adding a tooltip
  155. Adding new data to our old globe
  156. Coloring the globe
  157. Adding a tooltip
  158. The HTML
  159. Building the static parts of the tooltip
  160. Showing and hiding the tooltip
  161. Summary
  162. Shaping Maps with Data - Hexbin Maps
  163. Reviewing map visualization techniques
  164. Choropleth maps
  165. Cartograms
  166. Dot density maps
  167. Value and use of the hexagon
  168. Making a hexbin map
  169. Reviewing the hexbin algorithm
  170. Setting it up
  171. Drawing the map
  172. Drawing a point grid for our hexagons
  173. Keeping only the points within the map
  174. Making the hex tile
  175. Retrieving the hexagon center points
  176. Drawing the hex tiles
  177. Joining data points to the layout points
  178. Dressing our data for the final act
  179. Turning our visual into an interactive app
  180. Adding additional information on hover and click
  181. Changing the hexagon size
  182. Changing the color scale interpolator
  183. Browsing different datasets
  184. Encoding data as hexagon size
  185. Summary
  186. Publishing Your Visualization with Github Pages
  187. What we will publish
  188. Understanding the type of content you can publish
  189. Hosting your code on GitHub
  190. Making sense of some key terms and concepts
  191. Tracking historic changes of your files
  192. Collaborating on a project
  193. Working on project branches
  194. Setting up a GitHub account
  195. Creating a repository
  196. Editing a file on GitHub
  197. Uploading files to the repository
  198. Publishing your project on GitHub Pages
  199. Preparing the files for publishing
  200. Keeping your paths absolute
  201. Changing the main HTML filename to index.html
  202. Publishing your project
  203. Summary

An example with viz.js

To see this in practice, let's take a look at the scripts/viz.js program as a template for creating testable code for the data manipulation functions in the visualization. For this example, we will create a set of simple bars that are based on the profit of an arbitrary dataset. We are given the sales and cost in the data; however, we need to determine the profit for the visualization by subtracting the sales from the cost. In this contrived example, we need a few small helper functions, which are as follows:

  • A function to take the original dataset and return a new dataset with the profit calculated
  • A function to retrieve an array of unique categories to apply to an ordinal scale
  • A function to determine the maximum profit value in order to build the upper bound of our input domain

If we create these functions with the best practices outlined earlier and expose them externally, we can test them in isolation and independently.

Let's take a tour of the script to see how it all works together:

if (d3.charts === null || typeof(d3.charts) !== 'object') 
{ d3.charts = {}; }

Here, we will define the namespace for the chart. In this example, our chart can be instantiated with d3.charts.viz. If the d3 object with the charts property does not exist, or if it is not of the type object, create it, using classical functional inheritance to leverage common patterns from a base function:

d3.charts.viz = function () { 
  // Functional inheritance of common areas 
  var my = d3.ext.base(); 

A handy function (see base.js) to quickly assign getters/setters to the closure following the pattern in Towards Reusable Charts is as follows:

  // Define getter/setter style accessors.. 
  // defaults assigned 
  my.accessor('example', true); 

We use the svg variable at this level of scope to maintain state when quickly appending selectors. The void 0 is a safer way to initialize the variable as undefined:

  // Data for Global Scope 
  var svg = void 0, 
      chart = void 0; 

Define the D3 instance functions that will be used throughout the visualization:

  // Declare D3 functions, also in instance scope 
  var x = d3.scale.linear(), 
      y = d3.scale.ordinal(); 

The following function represents the main interface to the outside world. There is also a set of setup functions commonly seen in D3 visualizations. The SVG container is set up in a way that can easily look for existing SVG containers in the selector and rebind the data. This makes it much easier to redraw when making subsequent calls with new data:

  my.draw = function(selection) { 
    selection.each(function(data) { 
      // code in base/scripts.js 
      // resuable way of dealing with margins 
      svg = my.setupSVG(this); 
      chart = my.setupChart(svg); 
 
      // Create the visualization 
      my.chart(data); 
    }); 
  }; 
 
  // main method for drawing the viz 
  my.chart = function(data) { 
    var chartData = my.profit(data); 
 
    x.domain([0, my.profitMax(chartData)]) 
        .range([0,my.w()]); 
    y.domain(my.categories(chartData)) 
        .rangeRoundBands([0, my.h()], 0.2); 
 
    var boxes = chart.selectAll('.box').data(chartData); 
 
    // Enter 
    boxes.enter().append('rect') 
        .attr('class', 'box') 
        .attr('fill', 'steelblue'); 
 
    // Update 
    boxes.transition().duration(1000) 
        .attr('x', 0) 
        .attr('y', function(d) { return y(d.category) }) 
        .attr('width', function(d) {  return x(d.profit) }) 
        .attr('height', y.rangeBand()) 
 
    // Exit 
    boxes.exit().remove(); 
  }; 

Notice that the chart function relies on several helper functions (shown in the following lines of code) to work with the data. It is also written in such a way that we can take advantage of the enter/update/exit pattern:

  // Example function to create profit. 
  my.profit = function(data) { 
    return data.map(function(d) { 
      d.profit = parseFloat(d.sales) - parseFloat(d.cost); 
      return d; 
    }); 
  }; 

This function is used to create a new data structure that has profit assigned. Note that it takes one data array in as a parameter and returns a newly constructed array with the profit attribute added. This function is now exposed externally with viz().profit(data) and can be easily tested. It does not change any of the outside global variables. It is just data in and new data out:

  my.categories = function(data) { 
    return data.map(function(d) { 
      return d.category; 
    }); 
  }; 

This is the exact same pattern as my.profit(data). We will take the data structure in as input and return a new data structure, that is, an array of all the categories. In the preceding lines of code, you saw that this is leveraged to create the input domain.

  my.profitMax = function(data) { 
    return d3.max(data, function(d) { return d.profit; }); 
  }; 

Once again, a simple function to take data in, compute the max, and return that maximum value. It is very easy to test and verify with d3.charts.viz().profitMax(data)?

   return my; 
  };