Chapter 66: Plot D3.js
1. What is D3.js actually? (Clear definition first)
D3.js (stands for Data-Driven Documents) is the most powerful and flexible JavaScript library for creating custom, interactive data visualizations (charts, graphs, maps, diagrams, animations) directly in web pages.
Unlike Chart.js or Google Charts (which give you ready-made chart types with one function call), D3.js is not a charting library — it is a data manipulation + DOM manipulation library that lets you:
- Bind data to HTML/SVG elements
- Create any visual shape you can imagine (not just bar/line/pie)
- Control every single pixel, animation, transition, interaction
- Make visualizations that are completely custom (force-directed networks, geographic maps, hierarchical trees, particle systems, liquid charts…)
In simple words:
- Chart.js / Google Charts = “give me a bar chart in 10 lines”
- D3.js = “give me full control to build exactly the chart I want, even if it takes 100 lines”
Because of this power, D3.js is:
- The industry standard for complex/custom data viz
- Used by New York Times, Washington Post, The Pudding, Observable, Fivethirtyeight, Bloomberg…
- Very common in data science portfolios, UX/UI interviews, and advanced web development jobs
2. Why students find D3.js difficult at first (and why it’s worth learning)
- Steep learning curve — you must understand SVG, data binding, enter/update/exit pattern, scales, axes, transitions
- No “one function = one chart” — you build everything manually
- Requires good JavaScript knowledge (arrays, objects, functions, DOM)
But once you get past the first 2–3 weeks, it becomes very addictive — you realize you can make anything.
3. Your First D3.js Plot – Hello World Bar Chart (Copy-Paste & Run)
Create a file called d3-hello.html and paste this complete code:
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>D3.js – Hello World Bar Chart</title> <style> body { background: #f0f4f8; font-family: Arial, sans-serif; display: flex; flex-direction: column; align-items: center; padding: 20px; } svg { background: white; border-radius: 12px; box-shadow: 0 10px 30px rgba(0,0,0,0.15); } h1 { color: #2c3e50; margin-bottom: 10px; } </style> <!-- Load D3.js from CDN --> <script src="https://d3js.org/d3.v7.min.js"></script> </head> <body> <h1>My First D3.js Bar Chart</h1> <p>Fruit sales this month (hover to see values)</p> <svg id="chart" width="700" height="400"></svg> <script> // 1. Select SVG container const svg = d3.select("#chart"); // 2. Our data const data = [ { fruit: "Apple", sales: 45 }, { fruit: "Banana", sales: 32 }, { fruit: "Orange", sales: 28 }, { fruit: "Mango", sales: 51 }, { fruit: "Grapes", sales: 19 } ]; // 3. Set margins (leave space for axes & labels) const margin = { top: 60, right: 40, bottom: 60, left: 60 }; const width = +svg.attr("width") - margin.left - margin.right; const height = +svg.attr("height") - margin.top - margin.bottom; // 4. Create inner group (g) with margins applied const g = svg.append("g") .attr("transform", `translate(${margin.left}, ${margin.top})`); // 5. Create scales (map data values → pixels) const xScale = d3.scaleBand() .domain(data.map(d => d.fruit)) .range([0, width]) .padding(0.2); const yScale = d3.scaleLinear() .domain([0, d3.max(data, d => d.sales)]) .range([height, 0]); // 6. Draw X axis g.append("g") .attr("transform", `translate(0, ${height})`) .call(d3.axisBottom(xScale)); // 7. Draw Y axis g.append("g") .call(d3.axisLeft(yScale)); // 8. Draw bars g.selectAll(".bar") .data(data) .enter() .append("rect") .attr("class", "bar") .attr("x", d => xScale(d.fruit)) .attr("y", d => yScale(d.sales)) .attr("width", xScale.bandwidth()) .attr("height", d => height - yScale(d.sales)) .attr("fill", "#36a2eb") .on("mouseover", function() { d3.select(this).attr("fill", "#ff6384"); }) .on("mouseout", function() { d3.select(this).attr("fill", "#36a2eb"); }); // 9. Title svg.append("text") .attr("x", canvas.width / 2) .attr("y", 30) .attr("text-anchor", "middle") .style("font-size", "24px") .style("font-weight", "bold") .text("Fruit Sales This Month"); // 10. Axis labels svg.append("text") .attr("x", margin.left + width / 2) .attr("y", canvas.height - 10) .attr("text-anchor", "middle") .text("Fruit"); svg.append("text") .attr("transform", "rotate(-90)") .attr("x", - (margin.top + height) / 2) .attr("y", 20) .attr("text-anchor", "middle") .text("Sales (dozens)"); </script> </body> </html> |
What you see:
- Clean bar chart with blue bars
- Hover on bar → changes color (simple interaction)
- Axes, title, labels — looks professional
- No external libraries except D3.js CDN
4. Step-by-Step: How We Made This Plot (Blackboard Style)
- Include D3.js<script src=”https://d3js.org/d3.v7.min.js”></script>
- Select SVGd3.select(“#chart”)
- Data Array of objects (most common format)
- ScalesscaleBand() for categorical x-axis scaleLinear() for numeric y-axis
- Axesd3.axisBottom(xScale) + call()
- BarsselectAll(“.bar”) + data() + enter() + append(“rect”) → This is the famous enter-update-exit pattern — the heart of D3.js
- Events.on(“mouseover”, …) — simple hover effect
5. Teacher’s Quick Tips (Hyderabad Student Style 😄)
- Start with v7 (current stable) — syntax changed a lot from v3/v4/v5/v6
- Use d3.select() and d3.selectAll() — D3 is all about selecting & manipulating DOM/SVG
- Common mistake #1: Forget .enter() → bars don’t appear
- Common mistake #2: Wrong scale domain/range → bars upside down or off-screen
- Pro tip: Use d3.scaleBand().padding(0.2) — nice gap between bars
- Pro tip 2: Add transitions for animation
|
0 1 2 3 4 5 6 7 8 9 |
.attr("y", height) // start at bottom .transition() .duration(1000) .attr("y", d => yScale(d.sales)); |
Understood how to plot with D3.js now? D3.js is the most powerful plotting tool — it gives you full control, but requires more code than Chart.js or Plotly. Once you master it, you can build almost any visualization imaginable.
Tell me honestly — what do you want next?
- Line chart with smooth curve & tooltips?
- Interactive scatter plot with zoom/pan?
- Force-directed network graph (D3.js specialty)?
- How to load CSV/JSON data into D3?
- Or 20-question D3.js quiz?
Just say — we can build any D3 visualization together step by step! 🚀
