A chart is a translation: a category becomes a position, a number becomes a length, and labels tell the reader what those marks mean. D3 is very good at that translation. Svelte is very good at turning state into elements on a page. We will give each one that job.
Our question is “Which day did this café sell the most cups?” We will use seven invented daily totals, not a real business dataset. A bar chart is a good fit because we are comparing amounts across a small set of categories. Keeping weekdays in calendar order tells a different story from ranking them by sales; our finished chart lets the reader choose.
Try the button, then open the data table. This is the actual component you will build.
View the data
| Day | Cups sold |
|---|---|
| Mon | 42 |
| Tue | 58 |
| Wed | 36 |
| Thu | 67 |
| Fri | 85 |
| Sat | 94 |
| Sun | 73 |
You need: a little JavaScript (arrays, objects, functions), basic HTML/CSS, a terminal, an editor, and a current Node.js LTS installation with npm. You do not need previous D3 experience. This tutorial uses Svelte 5 runes; older examples using reactive $: declarations have different syntax.
How to work: build along through the six lessons below. Short code blocks are edits or excerpts, with their location stated. The complete, working file is at the end if you need to compare. Allow 90 minutes; the CSV extension is optional.
| Lesson | Time | You will leave with |
|---|---|---|
| 1. Give each tool a job | 10 min | A running Svelte app |
| 2. Draw one bar | 10 min | A useful model of SVG coordinates |
| 3. Translate data with scales | 20 min | Seven correctly sized bars |
| 4. Make the chart readable | 15 min | Axes, units, and values |
| 5. Make it react | 20 min | Sorting, responsive layout, and accessible data |
| 6. Check and extend it | 15 min | A verified chart and a small independent challenge |
1. Give each tool a job
Many D3 tutorials use selections, .append(), and .join() to create DOM elements. Those are useful APIs, but Svelte already creates and updates elements. In this workshop, D3 owns the maths; Svelte owns the markup. We import scale functions from D3 and put ordinary SVG elements in a Svelte template. There is no DOM selection, mount hook, or effect to keep in sync.
Create a new app using the official Svelte CLI:
npx sv create first-d3-chart --template minimal --types ts --no-add-ons --install npm
cd first-d3-chart
npm install d3@7
npm install -D @types/d3@7
npm run dev -- --open Keep that terminal running. d3 contains the runtime functions; @types/d3 provides TypeScript declarations. In an existing Svelte 5 project, install those two dependencies and use a new route instead of replacing an existing page.
Create src/lib/BarChart.svelte. For now, put this in it:
<p>The chart will go here.</p> Replace src/routes/+page.svelte with:
<script lang="ts">
import BarChart from '$lib/BarChart.svelte';
</script>
<main>
<h1>Your first D3 chart</h1>
<BarChart />
</main>
<style>
main { max-width: 760px; margin: 40px auto; padding: 0 16px; }
</style> Checkpoint: your browser shows the heading and placeholder. If it does not, fix the app setup before adding chart code. Check the terminal for the actual local URL; Vite can choose a different port when one is already in use.
2. Draw one bar: SVG coordinates
SVG gives us a drawing surface with coordinates. The origin is at the top left. Moving right increases x; moving down increases y. A rectangle’s x and y locate its top-left corner, while width and height describe its size.
Replace all of src/lib/BarChart.svelte with this tiny experiment:
<svg viewBox="0 0 640 360" role="img" aria-label="One bar, 126 units tall">
<line x1="48" x2="624" y1="316" y2="316" stroke="#85857e" />
<rect x="64" y="190" width="64" height="126" fill="#21766b" />
</svg>
<style>
svg { display: block; width: 100%; height: auto; }
</style> The baseline is at y = 316. The bar starts at y = 190, so its height is 316 − 190 = 126. Notice that its height is not 190. This subtraction is the most common source of first-chart bugs.
viewBox="0 0 640 360" defines internal drawing units. CSS controls how large the SVG appears on screen. At 320 CSS pixels wide, each drawing unit is half a CSS pixel. We will keep the drawing coordinates stable as the container changes size.
We also reserve margins: 48 units on the left for numbers, 44 at the bottom for weekday labels, 32 at the top for values and a unit label, and 16 on the right. Our plotting rectangle therefore runs from x = 48 to 624 and y = 32 to 316. All coordinates in this tutorial include those margins; do not add a translated group as well.
Try it: change the bar’s y to 130 and its height to 186. Its top moves up, but its bottom should stay on the baseline. Then restore the original values.
3. Translate data with scales
Hard-coded coordinates work for one rectangle. Scales let the same rules work for every row. A domain is the input values; a range is the output positions.
Replace the entire component again with this first data-driven version:
<script lang="ts">
import { max, scaleBand, scaleLinear } from 'd3';
// Invented data: cups sold by one café during one week.
const data = [
{ day: 'Mon', cups: 42 },
{ day: 'Tue', cups: 58 },
{ day: 'Wed', cups: 36 },
{ day: 'Thu', cups: 67 },
{ day: 'Fri', cups: 85 },
{ day: 'Sat', cups: 94 },
{ day: 'Sun', cups: 73 },
];
const width = 640;
const height = 360;
const margin = { top: 32, right: 16, bottom: 44, left: 48 };
const bottom = height - margin.bottom;
const x = scaleBand<string>()
.domain(data.map((d) => d.day))
.range([margin.left, width - margin.right])
.padding(0.2);
const y = scaleLinear()
.domain([0, max(data, (d) => d.cups) || 1])
.nice()
.range([bottom, margin.top]);
</script>
<svg viewBox={`0 0 ${width} ${height}`} role="img" aria-label="Daily café sales; labels added in the next lesson">
{#each data as d (d.day)}
<rect
x={x(d.day)}
y={y(d.cups)}
width={x.bandwidth()}
height={y(0) - y(d.cups)}
fill="#21766b"
/>
{/each}
</svg>
<style>
svg { display: block; width: 100%; height: auto; }
</style> The band scale allocates a slot to each weekday. x('Mon') gives the left edge of Monday’s bar; x.bandwidth() gives the bar width. Padding leaves space between bars. It is a proportion of the band step, not a number of pixels. The scale’s domain determines the left-to-right order.
The linear scale maps cups to vertical positions. Its range is deliberately reversed: zero goes to the bottom, and larger values go upwards. .nice() expands the domain to round bounds; for this data it becomes 0–100. The || 1 fallback avoids a collapsed 0–0 domain if all values are zero, and handles max returning undefined for an empty array. It does not validate malformed data.
For Monday, the resulting position is approximately y = 196.72. The rectangle’s height is 316 − 196.72 = 119.28 drawing units. D3 can return fractional positions; SVG handles them.
Bar length encodes magnitude, so the value axis starts at zero. Starting at 30 would exaggerate differences in cups sold. This example expects finite, non-negative numbers and unique weekday labels; negative values need bars on both sides of a zero baseline.
Checkpoint: seven bars appear; Saturday is tallest, Wednesday shortest. Set Monday’s cups to zero: its bar should disappear into the baseline, not stretch to the top. Restore 42 before continuing.
4. Make the chart readable
A reader should not have to guess the scale or hover to discover basic values. We will add a unit label, horizontal grid lines, a vertical numeric axis, and weekday labels.
Add this after the y scale in your script:
const ticks = y.ticks(5); Inside <svg>, before the bar loop, insert:
<text x={margin.left} y="16">Cups sold</text>
{#each ticks as tick (tick)}
<line
x1={margin.left} x2={width - margin.right}
y1={y(tick)} y2={y(tick)}
stroke={tick === 0 ? '#85857e' : '#deded5'}
/>
<text x={margin.left - 10} y={y(tick)} dy="0.32em" text-anchor="end">
{tick}
</text>
{/each} SVG paints later elements on top of earlier ones, so this puts the grid behind the bars. The tick count is a hint: ticks(5) produces six ticks here, including both endpoints. Each label and grid line uses the same y(tick) as the chart.
Inside the bar loop, after each <rect />, add:
<text x={(x(d.day) ?? 0) + x.bandwidth() / 2}
y={y(d.cups) - 8} text-anchor="middle">
{d.cups}
</text>
<text x={(x(d.day) ?? 0) + x.bandwidth() / 2}
y={bottom + 24} text-anchor="middle">
{d.day}
</text> Add this rule to the component’s style block:
text { fill: #42483f; font: 13px system-ui, sans-serif; } Half a bandwidth puts the label at the bar’s centre. A band scale can return undefined for a category outside its domain, which is why TypeScript needs a fallback before arithmetic. Here every row is in the domain, so that fallback is never used. If categories unexpectedly appear at the left edge in your own chart, fix the domain rather than relying on the fallback.
We have built axes out of SVG primitives. D3’s axisLeft and axisBottom are another option, but they create DOM nodes through selections. Rendering ticks in Svelte keeps element ownership consistent and makes the styling visible in the template.
Checkpoint: all bars share the zero baseline; labels sit above their bars; the axis says “Cups sold”. If the grid covers the bars, move its loop earlier in the SVG.
5. Make it react, and make it usable
Sorting gives us a useful test of the D3/Svelte boundary. Add these declarations after data in the script:
let sorted = $state(false);
let rows = $derived(sorted ? [...data].sort((a, b) => b.cups - a.cups) : data); $state marks a value that can change. $derived expresses a value calculated from reactive inputs. Copying the array before .sort() preserves the original weekday order for the reset button.
Replace the const x = ... declaration with:
let x = $derived(
scaleBand<string>()
.domain(rows.map((d) => d.day))
.range([margin.left, width - margin.right])
.padding(0.2),
); Change the bar loop’s input from data to rows, keeping (d.day) as its key. Svelte’s keyed each blocks use that unique value to retain each day’s identity as rows move. Avoid the array index as a key for a sortable list.
Put this button immediately before the SVG:
<button type="button" aria-pressed={sorted} onclick={() => (sorted = !sorted)}>
{sorted ? 'Restore weekday order' : 'Sort by cups sold'}
</button> A click changes sorted, which changes rows, which rebuilds x. Svelte updates the positions. The y scale stays fixed because sorting changes order, not the data values. If you later allow data edits or filtering, make the relevant data and scales reactive too. Mutating a D3 scale’s domain in an event handler is less clear than deriving a fresh scale from state.
Finish the surrounding component
Use the complete file below to add the remaining presentation and accessibility pieces, or compare it with your own code. It is the same source used by the live chart above.
- A figure caption names the chart and identifies the data as invented.
- The SVG has an accessible summary. Its decorative inner group is hidden from assistive technology; an HTML table provides every value in reading order.
- Values are visible above the bars. There is no essential information available only on hover or through colour.
- A native button supports keyboard activation, exposes its pressed state, and has a visible focus ring. Native disclosure controls open the data table.
- The SVG scales with its container. Below 480 pixels, its wrapper scrolls horizontally to keep labels readable. This is a deliberate trade-off for a first chart: the whole page should never scroll sideways. A more advanced chart can measure its container and recompute the scale ranges.
The SVG description is written for this fixed dataset. If you replace the data, update the description as well as the visible labels and table. Empty datasets should receive an explicit “No data available” message in a production component.
Complete BarChart.svelte — copy this entire file
<script lang="ts">
import { max, scaleBand, scaleLinear } from 'd3';
// Invented workshop data: cups sold by one café in one week.
const data = [
{ day: 'Mon', cups: 42 },
{ day: 'Tue', cups: 58 },
{ day: 'Wed', cups: 36 },
{ day: 'Thu', cups: 67 },
{ day: 'Fri', cups: 85 },
{ day: 'Sat', cups: 94 },
{ day: 'Sun', cups: 73 },
];
let sorted = $state(false);
let rows = $derived(sorted ? [...data].sort((a, b) => b.cups - a.cups) : data);
const width = 640;
const height = 360;
const margin = { top: 32, right: 16, bottom: 44, left: 48 };
const bottom = height - margin.bottom;
let x = $derived(
scaleBand<string>()
.domain(rows.map((d) => d.day))
.range([margin.left, width - margin.right])
.padding(0.2),
);
const y = scaleLinear()
.domain([0, max(data, (d) => d.cups) || 1])
.nice()
.range([bottom, margin.top]);
const ticks = y.ticks(5);
</script>
<figure class="chart">
<figcaption>
<strong>A week at the café</strong>
<span>Cups sold per day · invented workshop data</span>
</figcaption>
<button type="button" aria-pressed={sorted} onclick={() => (sorted = !sorted)}>
{sorted ? 'Restore weekday order' : 'Sort by cups sold'}
</button>
<div class="plot-scroll">
<svg
viewBox={`0 0 ${width} ${height}`}
role="img"
aria-label="Cups sold by day. Saturday is highest at 94 cups; Wednesday is lowest at 36. Exact values are in the table below."
>
<g aria-hidden="true">
<text x={margin.left} y="16" class="unit">Cups sold</text>
{#each ticks as tick (tick)}
<line
x1={margin.left}
x2={width - margin.right}
y1={y(tick)}
y2={y(tick)}
stroke={tick === 0 ? '#85857e' : '#deded5'}
/>
<text x={margin.left - 10} y={y(tick)} dy="0.32em" text-anchor="end">{tick}</text>
{/each}
{#each rows as d (d.day)}
<rect
x={x(d.day)}
y={y(d.cups)}
width={x.bandwidth()}
height={y(0) - y(d.cups)}
fill="#21766b"
/>
<text
x={(x(d.day) ?? 0) + x.bandwidth() / 2}
y={y(d.cups) - 8}
text-anchor="middle"
class="value">{d.cups}</text
>
<text x={(x(d.day) ?? 0) + x.bandwidth() / 2} y={bottom + 24} text-anchor="middle"
>{d.day}</text
>
{/each}
</g>
</svg>
</div>
<details>
<summary>View the data</summary>
<table>
<caption>Café sales — cups per day (invented)</caption>
<thead><tr><th scope="col">Day</th><th scope="col">Cups sold</th></tr></thead>
<tbody>
{#each rows as d (d.day)}
<tr><th scope="row">{d.day}</th><td>{d.cups}</td></tr>
{/each}
</tbody>
</table>
</details>
</figure>
<style>
.chart {
margin: 0;
padding: 24px;
border: 1px solid #deded5;
border-radius: 8px;
background: #fafaf5;
color: #242820;
font-family: system-ui, sans-serif;
}
figcaption strong {
display: block;
font-size: 24px;
line-height: 1.25;
}
figcaption span {
display: block;
margin-top: 6px;
font-size: 13px;
}
button {
margin: 18px 0 8px;
padding: 9px 14px;
border: 1px solid #21766b;
border-radius: 4px;
background: white;
color: #17574f;
font: inherit;
font-size: 14px;
cursor: pointer;
}
button[aria-pressed='true'] {
background: #21766b;
color: white;
}
button:focus-visible,
summary:focus-visible {
outline: 3px solid #b45424;
outline-offset: 4px;
}
.plot-scroll {
overflow-x: auto;
}
svg {
display: block;
width: 100%;
min-width: 480px;
height: auto;
}
text {
fill: #42483f;
font-size: 13px;
}
.unit {
font-size: 12px;
}
.value {
font-weight: 600;
}
details {
margin-top: 12px;
font-size: 14px;
}
summary {
cursor: pointer;
}
table {
width: 100%;
margin-top: 12px;
border-collapse: collapse;
font-size: 14px;
}
caption {
text-align: left;
margin-bottom: 8px;
}
th,
td {
padding: 5px 8px;
text-align: left;
border-bottom: 1px solid #deded5;
}
@media (max-width: 520px) {
.chart {
padding: 16px;
}
}
</style>
Save the component as src/lib/BarChart.svelte in your app. It has no dependencies on this site’s styles or components. Keep the +page.svelte wrapper from lesson 1.
Checkpoint: sort, then restore weekday order. Saturday should move from sixth to first and back again without changing height. Tab to the button and press Enter or Space. Open the table using the keyboard, too.
6. Check your chart, then make it yours
A chart can compile successfully and still mislead. Check the numbers as well as the code. In a second terminal, from the app directory, run:
npm run check
npm run build Then inspect the result in your browser:
| Check | Expected result |
|---|---|
| Initial order | Mon, Tue, Wed, Thu, Fri, Sat, Sun |
| Descending order | Sat, Fri, Sun, Thu, Tue, Mon, Wed |
| Baseline | Every bar begins at zero |
| Ratio | Monday’s 42-cup bar is half the height of an 84-cup bar |
| Keyboard | Sort and data disclosure work with a visible focus indicator |
| Narrow viewport | Chart scrolls inside its frame; the page does not overflow |
| Exact values | Table agrees with all seven visible labels |
Your turn: a second week
Replace the daily totals with 52, 48, 61, 70, 80, 90, 65. Before refreshing, predict the tallest and shortest bars and write down the descending order. Update the chart summary for the new week. Can you explain which scale changes when the data changes, and which changes when you sort?
Check your answer
Saturday is highest at 90; Tuesday is lowest at 48. Descending order is Sat, Fri, Thu, Sun, Wed, Mon, Tue. Editing the data changes the y positions and may change the numeric domain; sorting changes the x domain order. With these new values, the nice domain ends at 90 rather than 100. That is fine for one chart, but use a shared domain if comparing two weeks side by side.
When something looks wrong
| Symptom | First thing to inspect |
|---|---|
| Bars point down or have negative heights | Reverse the y range and use y(0) - y(value) |
| All bars are crowded at the left edge | Check that category strings exactly match the x domain |
| Sorting does nothing | Both rows and x must be derived; the template must loop over rows |
| Weekday order cannot be restored | Use [...data].sort(...), not data.sort(...) |
| Duplicate-key error | Each row needs a unique key; aggregate repeated days or add stable IDs |
| Labels are clipped | Increase the relevant margin, then recompute the scale range |
| Nothing renders | Read the terminal and browser errors; confirm the import path and installed dependencies |
Optional extension: read a CSV
Real CSV values arrive as strings. Parse and validate them before they reach a scale. To try this without adding asynchronous loading yet, import csvParse from d3 and replace the data declaration in the complete component with:
const csvText = `day,cups
Mon,42
Tue,58
Wed,36
Thu,67
Fri,85
Sat,94
Sun,73`;
const data = csvParse(csvText, (row) => {
const day = row.day?.trim();
const raw = row.cups?.trim();
const cups = Number(raw);
if (!day || !raw || !Number.isFinite(cups) || cups < 0) {
throw new Error('Each row needs a day and a non-negative numeric cups value.');
}
return { day, cups };
});
if (new Set(data.map((d) => d.day)).size !== data.length) {
throw new Error('Day labels must be unique.');
} The explicit blank check matters: Number('') is zero, but a missing observation is not the same as zero sales. The D3 CSV documentation describes row conversion; adapt the validation to your dataset. If you move to a fetched file later, add loading, error, and empty states, and derive the scales from the loaded data. Do not silently drop invalid rows and present the remainder as complete.
You now have the pieces to build other charts: decide which visual property represents each field, let D3 map values into drawing coordinates, and let Svelte render the result. For your next experiment, try horizontal bars for long category names, or a shared y domain for two weeks side by side.