D3.js v7 Reference & Cheatsheet
Learning Path
flowchart LR
A["D3Js Overview"] --> B["Core Concepts"]
B --> C["Intermediate Topics"]
C --> D["Advanced Topics"]
D --> E["Practical Applications"]
A --> F["You Are Here"]
style F fill:#f90,color:#fff
A complete D3.js v7 reference for daily development. Keep this open while coding D3.js visualizations for Doda Browser, DodaZIP, or Durga Antivirus Pro.
What’s in This Reference
This page is a comprehensive cheatsheet of D3.js v7 APIs organized by category. Use it as a quick lookup when building visualizations. Each section shows the most common methods and patterns you’ll use in production.
Selections
d3.select(selector) // First match
d3.selectAll(selector) // All matches
selection.attr(name, value) // Set attribute
selection.style(prop, value) // Set CSS
selection.text(value) // Set text
selection.html(value) // Set HTML
selection.append(tag) // Append child
selection.insert(tag, before) // Insert before
selection.remove() // Remove from DOM
selection.classed(name, bool) // Toggle class
selection.property(name, value) // DOM property
selection.datum(value) // Bind single datum
selection.data(values, keyFn) // Data join
selection.each(fn) // Iterate
selection.call(fn) // Call with selection
selection.select(selector) // Find descendant
selection.selectAll(selector) // Find all descendants
selection.filter(selector) // Filter
selection.sort(comparator) // Sort elements
selection.raise() // Move to front
selection.lower() // Move to back
selection.on("event", handler) // Event listener
selection.dispatch("event") // Dispatch event
selection.clone(deep) // Clone elements
selection.empty() // True if empty
selection.nodes() // Array of nodes
selection.node() // First node
selection.size() // Element count
Data Join
selection.data(values, keyFn)
.enter() // New data items
.append("tag")
.merge(selection) // Merge enter + update
selection.exit().remove() // Remove extra elements
selection.join("tag") // Simplified enter/update/exit (v5+)
Scales
Continuous
d3.scaleLinear().domain([0, 100]).range([0, 500])
d3.scalePow().exponent(2)
d3.scaleSqrt() // Same as pow(0.5)
d3.scaleLog().base(10)
d3.scaleTime() // Date values
d3.scaleSequential().interpolator(d3.interpolateViridis)
d3.scaleDiverging().interpolator(d3.interpolateRdBu)Discrete
d3.scaleOrdinal().domain(["A","B"]).range(["red","blue"])
d3.scaleBand().domain(["A","B","C"]).range([0, 500]).padding(0.1)
d3.scalePoint().domain(["A","B"]).range([0, 500]).padding(0.5)Scale Methods
scale(value) // Map data to visual
scale.invert(value) // Reverse mapping (linear only)
scale.domain([min, max]) // Input range
scale.range([min, max]) // Output range
scale.nice() // Round domain
scale.clamp(bool) // Clamp output
scale.copy() // Clone
// Band specific:
scale.bandwidth() // Width of band
scale.step() // Distance between band starts
scale.padding(inner, outer) // Set padding
Axes
d3.axisTop(scale)
d3.axisRight(scale)
d3.axisBottom(scale)
d3.axisLeft(scale)
axis.ticks(count, format) // Suggest tick count
axis.tickFormat(format) // Format labels
axis.tickSize(inner, outer) // Tick length
axis.tickPadding(padding) // Label offset
axis.tickValues(array) // Explicit values
axis.tickArguments([count, format])Shapes
d3.line().x(fn).y(fn).curve(d3.curveLinear)
d3.area().x(fn).y0(fn).y1(fn).curve(d3.curveMonotoneX)
d3.arc().innerRadius(r).outerRadius(r).startAngle(a).endAngle(a)
d3.symbol().type(d3.symbolCircle).size(64)
d3.pie().value(fn).sort(null).padAngle(0.02)
d3.ribbon().radius(r)
d3.linkHorizontal()
d3.linkVertical()
d3.linkRadial()Curve Types
d3.curveLinear // Straight segments (default)
d3.curveLinearClosed // Closed loop
d3.curveStep // Step function
d3.curveStepBefore // Step left
d3.curveStepAfter // Step right
d3.curveBasis // Bezier curve
d3.curveBasisClosed // Closed Bezier
d3.curveCardinal // Cardinal spline
d3.curveMonotoneX // Monotone in x (for time series)
d3.curveMonotoneY // Monotone in y
d3.curveNatural // Natural cubic spline
Symbols
d3.symbolCircle
d3.symbolCross
d3.symbolDiamond
d3.symbolSquare
d3.symbolStar
d3.symbolTriangle
d3.symbolWye
d3.symbolsFill // All filled symbols
d3.symbolsStroke // All stroked symbols
Colors
Sequential Interpolators
d3.interpolateViridis d3.interpolatePlasma
d3.interpolateTurbo d3.interpolateRainbow
d3.interpolateCool d3.interpolateWarm
d3.interpolateReds d3.interpolateBlues
d3.interpolateGreens d3.interpolateGreys
d3.interpolateOranges d3.interpolatePurples
d3.interpolateRdYlGn d3.interpolateSpectralCategorical Schemes
d3.schemeCategory10 // 10 colors
d3.schemeAccent // 8 colors
d3.schemeDark2 // 8 colors
d3.schemePaired // 12 colors
d3.schemePastel1 // 9 colors
d3.schemePastel2 // 8 colors
d3.schemeSet1 // 9 colors
d3.schemeSet2 // 8 colors
d3.schemeSet3 // 12 colors
Color Functions
d3.color(string) // Parse color
d3.rgb(r, g, b) // RGB color
d3.hsl(h, s, l) // HSL color
d3.lab(l, a, b) // LAB color
d3.hcl(h, c, l) // HCL color
d3.cubehelix(h, s, l) // Cubehelix
color.brighter(k) // Lighten
color.darker(k) // Darken
color.copy() // Clone
color.rgb() // To RGB
color.toString() // To CSS string
Transitions
selection.transition(name)
.duration(ms) // 750 default
.delay(ms) // 0 default
.ease(d3.easeCubicInOut) // Easing function
.attr(name, value) // Animate attribute
.style(name, value) // Animate style
.remove() // Remove after transition
.on("start", fn) // Transition events
.on("end", fn)
.on("interrupt", fn)
.transition() // Chain next transition
.selection() // Get selection from transition
.end() // Promise on end
.interrupt() // Stop immediately
d3.active(selection) // Current transition on selection
Easing Functions
d3.easeLinear
d3.easeQuadIn d3.easeQuadOut d3.easeQuadInOut
d3.easeCubicIn d3.easeCubicOut d3.easeCubicInOut
d3.easeSinIn d3.easeSinOut d3.easeSinInOut
d3.easeExpIn d3.easeExpOut d3.easeExpInOut
d3.easeCircleIn d3.easeCircleOut d3.easeCircleInOut
d3.easeBackIn d3.easeBackOut d3.easeBackInOut
d3.easeBounceIn d3.easeBounceOut d3.easeBounceInOut
d3.easeElasticIn d3.easeElasticOut d3.easeElasticInOutInteractions
Events
selection.on("click", handler)
selection.on("dblclick", handler)
selection.on("mouseover", handler)
selection.on("mouseout", handler)
selection.on("mousemove", handler)
selection.on("mousedown", handler)
selection.on("mouseup", handler)
selection.on("touchstart", handler)
selection.on("touchmove", handler)
selection.on("touchend", handler)
d3.pointer(event, container) // Get [x, y] coordinates
Drag
d3.drag()
.container(node)
.filter(event => true)
.touchable(bool)
.subject(event => point)
.clickDistance(0)
.on("start", handler)
.on("drag", handler)
.on("end", handler)Zoom
d3.zoom()
.scaleExtent([min, max]) // [0.5, 5] default
.translateExtent([[x0,y0],[x1,y1]])
.extent([[x0,y0],[x1,y1]])
.clickDistance(0)
.tapDistance(10)
.duration(250)
.interpolate(d3.interpolateZoom)
.on("start", handler)
.on("zoom", handler)
.on("end", handler)
// Transform object
d3.zoomIdentity // { x:0, y:0, k:1 }
d3.zoomTransform(node) // Get current transform
transform.x // Translate x
transform.y // Translate y
transform.k // Scale factor
transform.rescaleX(scale) // Create rescaled scale
transform.rescaleY(scale)
transform.toString() // CSS transform string
Geographies
d3.geoPath().projection(projection)
d3.geoMercator()
d3.geoEquirectangular()
d3.geoNaturalEarth1()
d3.geoOrthographic()
d3.geoAlbersUsa()
d3.geoStereographic()
d3.geoConicConformal()
projection.scale(100)
projection.translate([width/2, height/2])
projection.fitSize([w, h], geojson)
projection.fitExtent([[x0,y0],[x1,y1]], geojson)
projection.rotate([λ, φ, γ])
projection.center([λ, φ])Force Layout
d3.forceSimulation(nodes)
.force("link", d3.forceLink(links).id(fn).distance(n).strength(n))
.force("charge", d3.forceManyBody().strength(n))
.force("center", d3.forceCenter(x, y))
.force("collide", d3.forceCollide().radius(n))
.force("x", d3.forceX(x).strength(n))
.force("y", d3.forceY(y).strength(n))
.alpha(n) // Energy (0 to 1)
.alphaMin(n)
.alphaDecay(n)
.alphaTarget(n)
.velocityDecay(n)
.on("tick", handler)
.on("end", handler)
.restart()
.stop()
.nodes(newNodes)
.find(x, y, radius)Hierarchies
d3.hierarchy(data)
.sum(fn) // Compute values
.count() // Count leaves
.sort(comparator)
.ancestors()
.descendants()
.leaves()
.links()
.path(target)
d3.treemap().size([w, h]).padding(n).round(true)
d3.pack().size([w, h]).padding(n)
d3.partition().size([w, h])
d3.tree().size([w, h])
d3.cluster().size([w, h])
d3.stratify() // Tabular data → hierarchy
Data Loading
d3.csv(url, rowConverter) // Promise
d3.tsv(url, rowConverter) // Promise
d3.json(url) // Promise
d3.text(url) // Promise
d3.xml(url) // Promise
d3.html(url) // Promise
d3.image(url) // Promise
d3.blob(url) // Promise
d3.buffer(url) // Promise
Arrays
d3.min(array, accessor) // Minimum value
d3.max(array, accessor) // Maximum value
d3.extent(array, accessor) // [min, max]
d3.sum(array, accessor) // Sum
d3.mean(array, accessor) // Arithmetic mean
d3.median(array, accessor) // Median
d3.variance(array, accessor) // Variance
d3.deviation(array, accessor) // Standard deviation
d3.quantile(array, p) // Quantile
d3.least(array, comparator) // Minimum element
d3.greatest(array, comparator) // Maximum element
d3.leastIndex(array, comparator) // Index of minimum
d3.greatestIndex(array, comparator) // Index of maximum
d3.bisectLeft(array, value) // Insertion point (left)
d3.bisectRight(array, value) // Insertion point (right)
d3.bisectCenter(array, value) // Insertion point (center)
d3.ascending(a, b) // Sort ascending
d3.descending(a, b) // Sort descending
d3.sort(array, accessor) // Stable sort
d3.range(start, stop, step) // Generate sequence
d3.ticks(start, stop, count) // Axis tick values
d3.tickStep(start, stop, count) // Tick step size
d3.shuffle(array, start, end) // Fisher-Yates shuffle
d3.cross(a, b, reducer) // Cartesian product
d3.pairs(array, reducer) // Sliding window pairs
d3.permute(array, indices) // Reorder
d3.zip(a, b, ...) // Zip arrays
d3.transpose(matrix) // Matrix transpose
d3.merge(arrays) // Merge arrays
Collections (v6+)
d3.group(data, keyFn, ...) // Map of groups
d3.rollup(data, reduceFn, keyFn, ...) // Aggregated map
d3.flatGroup(data, keyFn, ...) // Array of [key, values]
d3.flatRollup(data, reduceFn, keyFn) // Array of [key, value]
d3.index(data, keyFn, ...) // Map by key (unique)
Binning
d3.bin()
.domain([min, max])
.thresholds(count) // Number or array
.value(accessor)
bin(values) // Array of bins [{x0, x1, length}]
Delimiter-Separated Values
d3.csvParse(string, rowConverter)
d3.csvParseRows(string, rowConverter)
d3.csvFormat(rows, columns)
d3.csvFormatBody(rows, columns)
d3.csvFormatRow(row)
d3.csvFormatValue(value)
d3.tsvParse(string, rowConverter)
d3.tsvFormat(rows, columns)
d3.dsvFormat(delimiter)Timers
d3.now() // Current time (high-res)
d3.timer(callback, delay, time) // Scheduled callback
d3.timeout(callback, delay, time) // Single-shot
d3.interval(callback, delay, time) // Repeating
timer.stop() // Cancel
timer.restart(callback, delay, time) // Restart
Formatting
d3.format(specifier)(value) // Format number
d3.formatPrefix(specifier, value) // SI prefix
d3.formatDefaultLocale(definition) // Set locale
// Specifiers
",d" // Integer: 1,234
"$,.2f" // Currency: $1,234.56
".0%" // Percentage: 50%
".2s" // SI: 1.2K (for 1,200)
"+.0f" // Sign: +123
"020d" // Zero-padded: 000000001234
Time Formatting
d3.timeFormat(specifier)(date) // Date to string
d3.timeParse(specifier)(string) // String to date
d3.utcFormat(specifier)(date) // UTC formatting
d3.utcParse(specifier)(string) // UTC parsing
// Specifiers
"%Y" // Year: 2024
"%m" // Month: 01-12
"%d" // Day: 01-31
"%b" // Month: Jan-Dec
"%B" // Month: January-December
"%a" // Weekday: Mon-Sun
"%A" // Weekday: Monday-Sunday
"%H" // Hour (24): 00-23
"%I" // Hour (12): 01-12
"%M" // Minute: 00-59
"%S" // Second: 00-59
"%%" // Literal %
Time Intervals
d3.timeMillisecond
d3.timeSecond
d3.timeMinute
d3.timeHour
d3.timeDay
d3.timeWeek
d3.timeMonth
d3.timeYear
d3.utcMillisecond
d3.utcSecond
d3.utcMinute
d3.utcHour
d3.utcDay
d3.utcWeek
d3.utcMonth
d3.utcYear
interval(date) // Floor to interval
interval.ceil(date)
interval.round(date)
interval.offset(date, step)
interval.range(start, stop, step)
interval.count(start, end)
interval.every(step)Random
d3.randomUniform(min, max)
d3.randomNormal(mean, dev)
d3.randomLogNormal(mean, dev)
d3.randomBates(n)
d3.randomIrwinHall(n)
d3.randomExponential(rate)
d3.randomPareto(alpha)
d3.randomBernoulli(p)
d3.randomGeometric(p)
d3.randomBinomial(n, p)
d3.randomGamma(k, theta)
d3.randomBeta(alpha, beta)
d3.randomWeibull(k, a, b)
d3.randomCauchy(a, b)
d3.randomPoisson(lambda)
d3.randomInt(min, max)Try It Yourself
Open Doda Browser, create a new HTML file, paste this quick test to verify D3.js is working:
<!DOCTYPE html>
<html>
<head>
<title>D3.js Quick Test</title>
</head>
<body>
<svg width="200" height="200" id="test"></svg>
<script src="https://d3js.org/d3.v7.min.js"></script>
<script>
d3.select("#test").append("circle")
.attr("cx", 100).attr("cy", 100)
.attr("r", 50).attr("fill", "steelblue");
console.log("D3.js v" + d3.version + " loaded successfully!");
</script>
</body>
</html>Common Mistakes Beginners Make
1. Skipping the Fundamentals
Many beginners jump straight to advanced topics without mastering the basics. Take time to understand the core concepts before moving on.
2. Not Practicing Enough
Reading tutorials without writing code leads to shallow understanding. Code along with every example and experiment on your own.
3. Ignoring Error Messages
Error messages tell you exactly what went wrong. Read them carefully — they usually point to the line and type of issue.
4. Copy-Pasting Without Understanding
It’s tempting to copy code from tutorials, but typing it yourself and understanding each line builds real skill.
5. Giving Up Too Early
Every developer hits frustrating bugs. Take breaks, ask for help, and remember that struggling is part of learning.
FAQ
{< faq >}
- What is D3Js Reference?
- D3Js Reference refers to the core concepts and practices used to build and manage modern web applications. Understanding it is essential for web developers.
- Do I need prior experience to learn D3Js Reference?
- Basic familiarity with web development concepts helps, but D3Js Reference can be learned step by step even as a beginner.
- How long does it take to learn D3Js Reference?
- With consistent practice, you can grasp the fundamentals in a few days to a week. Mastery takes ongoing practice and real-world projects.
- Where can I use D3Js Reference in real projects?
- D3Js Reference is used in a wide range of applications — from simple websites to complex enterprise systems, depending on the specific tools and technologies involved.
- What are common tools used with D3Js Reference?
- The specific tools depend on the technology stack, but version control (Git), package managers, and testing frameworks are commonly used alongside most development topics.
{< /faq >}
What’s Next
Review the full D3.js tutorial series:
| Tutorial | Focus |
|---|---|
| D3.js Basics | Setup, selections, data join |
| D3.js SVG | Shapes, paths, transformations |
| D3.js Scales & Axes | Scales, axes, color encodings |
| D3.js Charts | Bar, pie, line, scatter |
| D3.js Interactions | Transitions, drag, zoom |
| D3.js Data Handling | CSV, JSON, aggregation |
| D3.js Advanced | Maps, force layout, hierarchies |
Related topics: JavaScript, SVG, CSS, Data Visualization, React
Built by developers for developers. Used daily in Doda Browser, DodaZIP, and Durga Antivirus Pro.
What’s Next
Congratulations on completing this D3Js Reference tutorial! Here’s where to go from here:
- Practice daily — Consistency is more important than long study sessions
- Build a project — Apply what you learned by building something real
- Explore related topics — Check out other tutorials in the same category
- Join the community — Discuss with other learners and share your progress
Remember: every expert was once a beginner. Keep coding!
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro