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

Drawing a point grid for our hexagons

Our aim is to draw a hexagon grid across the US map. D3-hexbin will do this for us later, but it can only draw a hexagon where there are points. So, we need to feed points to it. These points won’t have any information value for our users. They will only be used to produce the layout. As such, we can distinguish two types of points we will need:

  • Layout points to produce the hexbin tiling
  • Datapoints to render the color-scaled information

We’ll get to the datapoints soon, but at this stage, we’re only concerned with our layout points. Once done, you will have produced this wonderfully regular pattern of points stretching across our entire drawing area:

A grid of many points over the US
You can view this step in the browser at https://larsvers.github.io/learning-d3-mapping-11-2 and the code example at 11_02.html.

In the next step, we will cut this grid to shape to fit the US silhouette, but let’s lay it out first. Note that this will be the most involved bit of the calculations. No rocket science, but don’t worry if it doesn’t click immediately. Things often become clearer once stepping through the code in the debugger and/or using a few console.log()’s. Anyway, here we go:

var points = getPointGrid(160);

getPointGrid() takes only one argument: the number of columns of points we want. That’s enough for us to calculate the grid. First, we will get the distance in pixels between each dot. The distance between each dot stands in for the distance between the hexagon centers. d3.hexbin() will calculate this for us precisely later, but, for now, we want to get a good approximation. So, if we decide to have 160 columns of dots and our width is 840, the maximum distance will be 840 / 160 = 5.25 pixels. We then calculate the number of rows. The height is 540, so we can fit in 540 / 5.25 rows, which equals 108 rows of dots if we round it down:

function getPointGrid(cols) {
var hexDistance = width / cols;
var rows = Math.floor(height / hexDistance);

hexRadius = hexDistance/1.5;

Next, we will calculate the hexRadius. This might look funny. Why divide the distance by 1.5? The D3-hexbin module will produce hexbins for us if we feed it points and a desired hexbin radius. The hexagon radius we set here should guarantee that the resulting hexagons are large enough to include at least one point of the grid we produce. We want a gap-free hexagon tiling after all. So, a tight grid should have a small radius, and a wide grid should have a wider radius. If we had a wide grid and a small radius, we wouldn’t get a hexagon for each point. There would be gaps.

Luckily, hexagons are regular shapes, and their dimensions and properties are nicely interconnected. The vertical distance between hexagon centers is 1.5 times its radius, the horizontal distance is √3 (roughly 1.73):

How hexagon distance and radius relate to each other

Our grid points work as a proxy of hexagon centers. As such they are not 'perfectly' laid out in the sense that their vertical distance is the exact same as their horizontal distance with 5.25 pixels. In a perfect hexagon grid the vertical distance would be a little shorter than the horizontal distance as you can see in above figure. In order to get a relatively tight mesh of hexagons on the base of our proxy grid, we should chose a safemeaning wideradius to pass to the D3-hexbin module which indeed will deliver a perfect hexagon grid. We can calculate this radius with the formulae in the preceding figure as well as our distance (5.25 pixel) by solving for Radius. When re-shuffling the equation for the vertical distance Distance = 1.5 * Radius becomes Radius = Distance / 1.5. In our case the distance is 5.25 / 1.5 = a radius of 3.5. Using the horizontal distance would have given us a less safe—meaning tighter—radius with 5.25 / √3 = 3.03, which in fact would produce a few gaps in our final tiling.

Next, we will create and return the grid immediatelywell, the coordinates for the grid that is:

return d3.range(rows * cols).map(function(el, i) {
return {
x: Math.floor(i % cols * hexDistance),
y: Math.floor(i / cols) * hexDistance,
datapoint: 0
}
});
} // end of getPointGrid() function

d3.range(rows * columns) creates an array with one element per dot. We then iterate through each dot with .map() returning an object with three properties: x, y, and datapoint. These properties will define each of our grid points. The x coordinate will increase by the hexDistance every point and reset to 0 for each row (or put differently, after it runs through all columns). The y coordinate will increase by the hexDistance for each new row.

Equally important, each of these grid points will get a property called datapoints, which we will set to 0. This property will distinguish all the layout points (0) from the data points (1) later, allowing us to focus on the latter.

Congratulations! This was the most difficult bit, and you’re still here proudly lifting a square grid of tomato-colored dots into the air.

Note that not crucial but extremely helpful is visualizing the grids and points we make on the way. Here’s a little function that draws points if they are stored in an array of objects with x and y properties:

function drawPointGrid(data) {
svg.append('g').attr('id', 'circles')
.selectAll('.dot').data(data)
.enter().append('circle')
.attr('cx', function(d) { return d.x; })
.attr('cy', function(d) { return d.y; })
.attr('r', 1)
.attr('fill', 'tomato');
}