Discussion 7: More D3, Mapbox
First: more advanced JS
Arrow functions
Traditional Function
Arrow Function (Concise)
Arrow Function ({} block)
Ternary operator
Equivalent if-else statement:
In this example:
Object expansion
In this example:
Object.defineProperty()
In this example:
Native JavaScript events vs. D3.js events
Native JavaScript events
Native JS events: standard browser events
Native JavaScript event examples
Event | Trigger |
click | Mouse click |
dblclick | Double click |
mouseover | Pointer enters (bubbles) |
mouseout | Pointer leaves (bubbles) |
mousemove | Mouse moves |
contextmenu | Right-click |
keydown | Key is pressed |
keyup | Key is released |
focus | Element gains focus |
blur | Element loses focus |
input | Input or textarea value changes |
D3.js events
Events using D3
D3-only events
Events using .on()
D3-only event examples:
D3.js-Only Event Examples
D3.js event examples
Feature / Behavior | Description | Typical Use Case |
d3.drag | Enables dragging behavior for elements | Move nodes, bars, shapes |
d3.zoom | Enables zooming and panning | Maps, scatterplots, timelines |
d3.brush | Enables area brushing for selection | Select ranges on scatterplots, timelines |
d3.pointer(event) | Returns pointer position relative to a container | Precise cursor tracking inside SVG/Canvas |
d3.dispatch | Custom event dispatcher for components | Trigger and manage user-defined events |
d3.timer | Frame-optimized custom timer (like requestAnimationFrame) | Continuous or custom animations |
d3.timeout | Timer that fires once after a delay | Trigger an action after delay |
d3.interval | Creates a repeating timer (like setInterval) | Loop animations, data refresh |
d3.brush().filter() | Controls when brush is allowed | Disable brushing on invalid inputs |
Grouping with D3.js
d3.map
d3.groups
Example result:
Key to group by
Key to group by
d3.rollup
Input (lines)
Output
Example
Aggregator applied to every group
Key to group by
Output of aggregator
Key
Aggregator comes first!
Comparing grouping functions
Function | Description | Returns | Use Case |
d3.group | Groups data by key(s) | Map | Organize data into groups, no aggregation |
d3.rollup | Groups and aggregates data by key(s) | Map | Get summary statistic per group |
d3.rollups/d3.groups | Same as group and rollup, but returns array format | Array of [key, value] pairs | Easier iteration over key-value pairs |
Mapbox GL JS
What is Mapbox GL?
Creating a Map
Map.on()
Syntax (where map is a mapboxgl.Map object):
map.on('load', async () => {
//code
});
What goes inside map.on()?
Inside:
Outside:
Checkoff - rollup()
What is the value of result after the following code runs?
Hint: d3.sum(v, fn) applies fn to every element of v and sums up the results.