85
D3.js (Data-Driven Documents) is a powerful JavaScript library for creating interactive and dynamic visualizations in web browsers.
This tutorial will walk you through installing D3.js and creating a basic chart with several code examples.
1. What is D3.js?
D3.js allows you to bind data to DOM elements and apply data-driven transformations. It works with HTML, SVG, and CSS to create highly customizable visualizations.
2. Installing D3.js
Option 1: CDN (Simplest Method)
Add the D3.js library directly to your HTML using a CDN (Content Delivery Network).
<script src="https://d3js.org/d3.v7.min.js"></script>
Benefits:
- No installation required.
- Always up-to-date.
Option 2: NPM (Node.js Installation for Advanced Users)
If you're working on a Node.js project, you can install D3.js using npm.
npm install d3
Usage in JavaScript:
import * as d3 from "d3";
Option 3: Download and Host Locally
- Download the D3.js library from the official site: https://d3js.org/.
- Extract and place the d3.min.js file into your project directory.
- Link it to your HTML:
<script src="path/to/d3.min.js"></script>
3. Basic D3.js Project Setup
HTML File Setup:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>D3.js Example</title> <script src="https://d3js.org/d3.v7.min.js"></script> <style> .bar { fill: steelblue; } </style> </head> <body> <h1 class="text-center">D3.js Basic Bar Chart</h1> <svg width="500" height="300"></svg> <script> // Sample data const data = [30, 70, 50, 100, 80]; // Select SVG and set dimensions const svg = d3.select("svg") .attr("width", 500) .attr("height", 300); // Create a scaling function const xScale = d3.scaleBand() .domain(data.map((d, i) => i)) .range([0, 500]) .padding(0.1); const yScale = d3.scaleLinear() .domain([0, d3.max(data)]) .range([300, 0]); // Create bars svg.selectAll("rect") .data(data) .enter() .append("rect") .attr("class", "bar") .attr("x", (d, i) => xScale(i)) .attr("y", d => yScale(d)) .attr("width", xScale.bandwidth()) .attr("height", d => 300 - yScale(d)); </script> </body> </html>
4. How the Code Works:
- SVG Creation:
d3.select(“svg”) targets the SVG element to draw the chart. - Scaling Functions:
d3.scaleLinear and d3.scaleBand ensure the chart scales properly to fit the data and SVG dimensions. - Bars (Rectangles):
svg.selectAll(“rect”) creates bars based on the dataset and appends them dynamically.
5. D3.js Concepts in Action
Example 1: Dynamic Circle Creation
<svg width="400" height="200"></svg> <script> const circleData = [10, 20, 30, 40]; const svg = d3.select("svg"); svg.selectAll("circle") .data(circleData) .enter() .append("circle") .attr("cx", (d, i) => (i + 1) * 80) .attr("cy", 100) .attr("r", d) .style("fill", "teal"); </script>
Explanation:
- Circles are dynamically created.
- cx (x-axis) positions each circle evenly.
- Radius (r) corresponds to data points.
Example 2: Adding Labels to Bars
svg.selectAll("text") .data(data) .enter() .append("text") .attr("x", (d, i) => xScale(i) + xScale.bandwidth() / 2) .attr("y", d => yScale(d) - 5) .attr("text-anchor", "middle") .text(d => d) .style("fill", "white");
Explanation:
- Adds data labels inside each bar.
- text-anchor: middle centers the text horizontally.
Example 3: Line Chart
<svg width="500" height="300"></svg> <script> const lineData = [10, 40, 60, 80, 120]; const x = d3.scaleLinear().domain([0, lineData.length - 1]).range([0, 500]); const y = d3.scaleLinear().domain([0, d3.max(lineData)]).range([300, 0]); const line = d3.line() .x((d, i) => x(i)) .y(d => y(d)) .curve(d3.curveBasis); // Smooth line svg.append("path") .datum(lineData) .attr("d", line) .attr("fill", "none") .attr("stroke", "steelblue") .attr("stroke-width", 2); </script>
6. Verifying Installation
After setting up the project, test your installation:
- Open the HTML file in your browser.
- If you see bars, circles, or lines as expected, D3.js is correctly installed and working.
7. Common Errors and Fixes
- Issue: d3 is not defined
Fix: Ensure the <script> tag is placed before the closing body tag or loaded through CDN properly. - Scaling Issues: Bars are too small or large.
Fix: Adjust the range in scaleLinear or scaleBand to match the SVG size.
8. Next Steps:
- Interactive Charts: Add tooltips, transitions, and mouse events.
- Complex Visualizations: Pie charts, force-directed graphs, and heatmaps.
- Real Data: Fetch and visualize API data using d3.json().