D3.js – Data-Driven Documents
D3.js (Data-Driven Documents) is a powerful JavaScript library for creating dynamic, interactive, and highly customizable data visualizations using HTML, SVG, and CSS.
Unlike chart libraries like Google Charts or Chart.js, D3 gives full control over every visual element, making it ideal for complex and unique visualizations.
Getting Started
1. Include D3.js in Your Project
<script src="<https://d3js.org/d3.v7.min.js>"></script>
2. Select an HTML Element
D3 uses CSS-style selectors to target elements:
d3.select("body").append("p").text("Hello D3!");
select()
→ Selects the first matching elementselectAll()
→ Selects all matching elementsappend()
→ Adds new elementstext()
→ Adds text content
Basic Data Binding
D3 binds data to DOM elements using data()
:
const data = [10, 20, 30, 40, 50];
d3.select("body")
.selectAll("p")
.data(data)
.enter()
.append("p")
.text(d => "Value: " + d);
data()
→ Binds an array of dataenter()
→ Creates new elements for each data pointd
→ Represents the current data item
Creating a Simple Bar Chart
<div id="chart"></div>
<script>
const data = [80, 120, 60, 150, 200];
const width = 500;
const height = 300;
const svg = d3.select("#chart")
.append("svg")
.attr("width", width)
.attr("height", height);
svg.selectAll("rect")
.data(data)
.enter()
.append("rect")
.attr("x", (d, i) => i * 60)
.attr("y", d => height - d)
.attr("width", 50)
.attr("height", d => d)
.attr("fill", "teal");
</script>
- Uses SVG rectangles to represent data
x
→ horizontal positiony
→ vertical position (SVG origin is top-left)height
→ height of each barfill
→ bar color
Scales and Axes
D3 provides scales to map data values to pixel values:
const xScale = d3.scaleBand()
.domain(data.map((d,i) => i))
.range([0, width])
.padding(0.1);
const yScale = d3.scaleLinear()
.domain([0, d3.max(data)])
.range([height, 0]);
svg.selectAll("rect")
.data(data)
.enter()
.append("rect")
.attr("x", (d, i) => xScale(i))
.attr("y", d => yScale(d))
.attr("width", xScale.bandwidth())
.attr("height", d => height - yScale(d))
.attr("fill", "orange");
scaleLinear()
→ Maps numerical data to pixelsscaleBand()
→ Maps categorical/indexed data to bands- Axes can be added using
d3.axisBottom()
andd3.axisLeft()
Advantages of D3.js
- Fully customizable visualizations
- Works directly with HTML, SVG, and CSS
- Powerful data binding and DOM manipulation
- Supports animations, transitions, and interactivity
- Handles large datasets efficiently
- Integrates with JSON, CSV, and APIs easily
When to Use D3.js
- Advanced data dashboards
- Custom charts not available in pre-built libraries
- Interactive maps and geospatial visualizations
- Animations and transitions in data
- Complex hierarchical visualizations (trees, sunbursts, network graphs)