D3.js Tutorial: Shop Sales Charts That Explain Themselves

Quick answer
D3.js is a JavaScript library for turning data into charts and graphics that live in the browser as SVG. This post builds a real one: a bar chart of a Karachi clothing shop's weekly sales by city, generated in Node with d3 and jsdom. You will see the scales that place each bar, the string price that broke the chart, and the one cleaning step that fixed it.
A clothing shop in Karachi sells in three cities, and every Monday the owner wants to know which city sold the most last week. The numbers live in a spreadsheet, one row per city, and should take ten seconds to read. Instead it takes a meeting: a table of figures hides the shape of the week. A bar chart answers fast: tall bar wins, short bar needs attention. But hand-built charts break quietly: one figure arrives as text, one bar vanishes, and nobody notices until a decision rests on wrong numbers. D3.js is the library JavaScript developers reach for when they want that control, and this post builds one for real.
What I would check before using it
My first check is whether the chart is standard or custom. D3.js is a set of building blocks, not a box of ready charts. If a plain bar, line, or pie chart is all you need, a charting library draws it in ten lines, and the Matplotlib: Charts in Python Without Opening a Spreadsheet post shows the same idea in Python. D3.js earns its keep when no ready-made chart does what you need.
My second check is where the chart will be read. D3.js draws SVG in the browser, so it fits dashboards and web pages. If the chart must be a static image in a weekly report, a Python script fits better, and the Streamlit Tutorial: Turn a Python Script Into a Dashboard post covers that route.
My third check is how comfortable the team is with JavaScript. D3.js is low level: you pick elements, bind data, and place them with scales. That control is the point, but it means reading real JavaScript whenever something looks wrong. If the team is still finding its feet, the JavaScript Explained: The Language That Runs the Whole Web post is where to start.
My fourth check is whether the data changes while people watch. D3.js has a data join that updates a chart in place when new numbers arrive, which suits live data. If the numbers refresh once a week, that strength goes unused.
My verdict, as judgement: adopt D3.js when you need a custom, interactive chart in the browser and someone will own the code. It flips when a standard chart would do, or the chart is a static image.
A Karachi clothing shop, charted by city
One week of sales from a small Karachi clothing shop: Karachi Rs 184,500, Lahore Rs 132,000, Islamabad Rs 96,000. The goal is a bar chart, one bar per city, built in Node.
Install d3 and jsdom; jsdom supplies the document D3.js expects in Node:
$ npm install d3 jsdom $ npm ls d3 jsdom batch66-d3js@1.0.0 +-- d3@7.9.2 `-- jsdom@31.0.1 The script builds the SVG, one rectangle per city:
const d3 = require("d3"); const { JSDOM } = require("jsdom"); const rawSales = [ { city: "Karachi", sales: 184500 }, { city: "Lahore", sales: "Rs 132,000" }, { city: "Islamabad", sales: 96000 }, ]; function cleanSales(value) { return Number(String(value).replace(/[^0-9.-]/g, "")); } const sales = rawSales.map((d) => ({ city: d.city, sales: cleanSales(d.sales) })); const total = d3.sum(sales, (d) => d.sales); console.log("Weekly total (Rs):", total); sales.forEach((d) => console.log(" ", d.city, "Rs", d.sales.toLocaleString("en-PK"))); const width = 560; const height = 320; const margin = { top: 20, right: 20, bottom: 40, left: 70 }; const innerWidth = width - margin.left - margin.right; const innerHeight = height - margin.top - margin.bottom; const dom = new JSDOM("<!DOCTYPE html><body></body>"); const body = d3.select(dom.window.document.body); const svg = body .append("svg") .attr("width", width) .attr("height", height) .attr("xmlns", "http://www.w3.org/2000/svg"); const chart = svg .append("g") .attr("transform", `translate(${margin.left},${margin.top})`); const x = d3 .scaleBand() .domain(sales.map((d) => d.city)) .range([0, innerWidth]) .padding(0.2); const y = d3 .scaleLinear() .domain([0, d3.max(sales, (d) => d.sales)]) .range([innerHeight, 0]); chart .selectAll("rect") .data(sales) .join("rect") .attr("x", (d) => x(d.city)) .attr("y", (d) => y(d.sales)) .attr("width", x.bandwidth()) .attr("height", (d) => innerHeight - y(d.sales)) .attr("fill", "#2563eb"); chart .selectAll("text") .data(sales) .join("text") .attr("x", (d) => x(d.city) + x.bandwidth() / 2) .attr("y", (d) => y(d.sales) - 6) .attr("text-anchor", "middle") .attr("font-family", "sans-serif") .attr("font-size", "13") .text((d) => "Rs " + d.sales.toLocaleString("en-PK")); console.log("Bar heights (px):"); sales.forEach((d) => { console.log(" ", d.city, "->", (innerHeight - y(d.sales)).toFixed(2)); }); console.log("SVG:"); console.log(body.html()); Two scales do the real work: the band scale turns city names into positions, and the linear scale turns rupee amounts into pixel heights. Its range is [innerHeight, 0], since SVG counts y downwards, so zero sits at the bottom.
My first run skipped cleaning, and Lahore's figure arrived as the string "Rs 132,000", as a spreadsheet export writes it:
$ node chart-buggy.js Weekly total (Rs): NaN Bar heights (px): Karachi -> 260 Lahore -> NaN Islamabad -> 135.28455284552848 The total came out NaN, and Lahore's bar vanished. The SVG shows why: the Lahore rectangle has height="NaN" and no y attribute, so the browser draws nothing. Number("Rs 132,000") is NaN, and NaN poisons everything it touches. The chart still looked half right, since d3.max quietly skips NaN values.
The fix is one small function, cleanSales, which strips everything except digits, a point, and a minus sign before converting. With that in place, the fixed run gave real numbers:
$ node chart.js Weekly total (Rs): 412500 Karachi Rs 184,500 Lahore Rs 132,000 Islamabad Rs 96,000 Bar heights (px): Karachi -> 260.00 Lahore -> 186.02 Islamabad -> 135.28 SVG: <svg width="560" height="320" xmlns="http://www.w3.org/2000/svg"><g transform="translate(70,20)"><rect x="29.375" y="0" width="117.5" height="260" fill="#2563eb"></rect><rect x="176.25" y="73.98373983739837" width="117.5" height="186.0162601626016" fill="#2563eb"></rect><rect x="323.125" y="124.71544715447153" width="117.5" height="135.28455284552848" fill="#2563eb"></rect><text x="88.125" y="-6" text-anchor="middle" font-family="sans-serif" font-size="13">Rs 184,500</text><text x="235" y="67.98373983739837" text-anchor="middle" font-family="sans-serif" font-size="13">Rs 132,000</text><text x="381.875" y="118.71544715447153" text-anchor="middle" font-family="sans-serif" font-size="13">Rs 96,000</text></g></svg> The numbers are clear: Karachi Rs 184,500 of Rs 412,500, Lahore Rs 132,000, Islamabad Rs 96,000, with bar heights to match, 260, 186.02, and 135.28. Check the computed numbers, not just the picture: a chart can look finished while a whole city is missing.
Common mistakes and how to fix them
First, feeding a scale a figure that is still text. The symptom is a total of NaN or a bar that never appears. The fix is to clean every figure to a number before it reaches a scale, and check it with Number.isFinite so a bad row fails loudly instead of vanishing.
Second, getting the y direction backwards. The symptom is bars hanging from the top of the chart. The fix is to remember SVG counts y downwards, so a linear scale for bar heights needs the range [innerHeight, 0] and the height is innerHeight - y(value).
Third, hand-writing the band scale's domain and missing a category. The symptom is a bar that never appears, because x returns undefined for a city outside the domain. The fix is to derive the domain from the data with sales.map((d) => d.city).
Fourth, running D3.js in Node without a document. The symptom is ReferenceError: document is not defined when you call d3.select. The fix is jsdom, as used here, which supplies a document for Node.
Frequently Asked Questions
Do I need a browser to use D3.js? No. This post ran in Node with jsdom standing in for the browser.
How is D3.js different from Chart.js? Chart.js hands you finished charts with a few lines of configuration, while D3.js hands you the pieces to build any chart. Pick Chart.js for standard charts, D3.js when the chart itself is the product.
Can D3.js handle data that keeps changing? Yes. Its data join updates the chart in place when new numbers arrive, which suits live dashboards. The WebSockets Explained: Real-Time Data Without Polling post covers fetching live data.
Is D3.js hard to learn? Harder than a charting library, because you learn selections, scales, and joins instead of one configuration object. Start with one bar chart.
What to remember
- D3.js builds charts from data with selections, scales, and joins.
- A band scale places categories; a linear scale turns numbers into pixel heights.
- Clean and validate every figure before it reaches a scale, because a string silently becomes NaN.
- Check the computed numbers, not just the picture.
Where this leaves you
One script, three cities, and a week of sales now reads in a second: Karachi Rs 184,500, Lahore Rs 132,000, Islamabad Rs 96,000, Rs 412,500 in total. The useful part was the failure, a string price that turned the total to NaN and erased a whole city from the chart without a single error message. Take numbers you already care about, your own sales, server costs, or signups, and chart them the same way, but print the totals first and trust the numbers before you trust the picture.
Further reading
- D3.js
- Getting started with D3
- D3 on GitHub
- JavaScript Explained: The Language That Runs the Whole Web
- Matplotlib: Charts in Python Without Opening a Spreadsheet
- Grafana Tutorial: Build a Dashboard That Shows the Truth
- Streamlit Tutorial: Turn a Python Script Into a Dashboard
- WebSockets Explained: Real-Time Data Without Polling
Waqas Shahid is a software engineer from Karachi with more than 12 years of experience, including 6+ years in engineering leadership. He writes The Practical Developer.
Originally published at https://practicaldevblog.blogspot.com/2026/12/d3js-shop-sales-chart.html
原文:https://www.a8q9.cn/en/article/d3-js-tutorial-shop-sales-charts-that-explain-themselves-16952f.html