D3.js is a low-level data visualisation library. For a high-level JavaScript library, use observable plot.
loading data
or within Observable notebook
data manipulation
- filter.
data.filter((d) => (d.Year === 2002) | (d.Year === 2019))
- grouping (by multiple columns).
grouped = d3.group(data_filtered, (d) => d.Sex, (d) => d.Year)
- returns a Map from key to array of value (or, using
groups
, an array of[key, value]
entries)
- returns a Map from key to array of value (or, using
- array manipulation
data joins
- D3 selections let you choose some HTML or SVG elements and change their style and/or attributes
d3.select
selects the first matching elementd3.selectAll
selects all matching elements
- Data join
- join an array of data to a D3 selection using following 4-stage (
select
,data
,join
,attr/style
) pattern:
- join an array of data to a D3 selection using following 4-stage (
shapes
D3 provides functions for drawing shapes:
d3.line
. draw lines between points , add curve.curve(d3.curveCardinal)
to interpolatenull
d3.area
. area betweeny=0
and lined3.stack
. stacked bar
scales and axes
- scale functions:
- continuous:
- linear (
scaleLinear
) - square root (
scaleSqrt
) - log (
scaleLog
) - time (
scaleTime
, domain is expressed as an array of dates)
- linear (
- continuous input to discrete output (
scaleQuantize
,scaleThreshold
) - discrete input to discrete output (
scaleOrdinal
)
- continuous:
d3.extent(data)
find domain and.nice()
to round values
- make an axis generator function using
d3.axisBottom
,d3.axisTop
,d3.axisLeft
ord3.axisRight
(and pass in your scale function) - format using
axis.ticks
oraxis.tickValues
maps
- GeoJSON. JSON-based format for specifying geographic data.
- projections. functions that convert from latitude/longitude
[lon, lat] -> [x, y]
. - geographic path generators (e.g.
d3.geoPath
,d3.geoCicle
). functions (shape generator) that convert GeoJSON shapes into SVG paths.
interaction and animation
- interaction
d3.handleMousemove
for hovering- for smaller items, use quadtree or Delaunay triangulation to find the nearest point
d3.drag
to move itemsd3.brush
for specifying an area
- transition
- add a
.transition()
call before the.attr
and.style
methods that you wish to transition .duration(2000)
in milliseconds and.delay(20)
, which can also accept a function to stagger delays- easing function (e.g.
.ease(d3.easeBounceOut)
) defines the change in speed of an element during a transition - transitions can be chained together by adding multiple calls to
.transition
- customise the path the elements take using a
.tween()
function - enter, exit, and update functions are required for fine-grained control of transitioning elements
- entering elements are newly created elements
- exiting elements are elements that are about to be removed
- add a
other
- hierarchies
- chord diagrams
- force layout to position elements using a physics-based simulator