Introduction to D3 and getting started

Learn what D3 is, how it differs from ECharts, and how to use SVG to build your first data-driven bar chart.

🎯 Introduction

In this article, you will learn what D3 is, how it differs from ECharts, and how SVG provides a drawing surface for charts. You will then install D3 in a Vue 3 project and build your first data-driven bar chart, working through the calculations that turn each value into a bar.


🧱 What is D3?

D3 stands for Data-Driven Documents. Breaking the name down makes its purpose clearer:

  • Data: A set of values, such as sales figures for a week.
  • Documents: Elements on a web page, such as rectangles and circles.
  • Driven: Data determines how those elements look: a larger value produces a taller bar.

D3 connects these ideas: bind data to page elements to turn values into visible graphics.


⚖️ Choosing between D3 and ECharts

If you already use ECharts, why learn another tool for drawing charts?

Think of ECharts as ready-made furniture and D3 as a woodworking toolbox. Ready-made furniture is usable immediately, but offers limited customization. A toolbox lets you build any furniture you want, provided you do the work yourself.

ComparisonEChartsD3
PurposeReady-made charting libraryLow-level visualization toolkit
UsageWrite a configuration objectAssemble the pieces yourself
Learning curveGentleSteeper
FlexibilityCustomize within supported chart typesBuild arbitrary graphics and interactions
Best suited toAdmin reports and standard business chartsCustom dashboards and creative visualizations
Choose ECharts for standard charts, and D3 for custom requirements that ECharts cannot meet. D3 can reproduce ECharts chart types, but the reverse does not hold.

🧱 Meet SVG: D3's drawing surface

The graphics D3 creates here are ordinary SVG elements. Before using D3, let's look at the output we want to produce.

This hand-written SVG draws two bars. No library is required; the browser renders it directly:

<svg width="300" height="300">
    <rect x="0" y="180" width="40" height="120" fill="#5470c6"></rect>
    <rect x="60" y="100" width="40" height="200" fill="#5470c6"></rect>
</svg>

rect represents a rectangle. These attributes define its appearance:

  • x, y: The position of its top-left corner.
  • width, height: Its dimensions.
  • fill: Its fill color.

Remember that SVG y coordinates increase downward, unlike the coordinate system used in mathematics:

(0,0) ───────────→ x axis (increases to the right)
  │
  │   y increases downward
  ▼
 y axis

To make a bar extend upward from the bottom, set y (its top edge) to the drawing height minus the value, and height to the value. With a height of 300 and a value of 120, the top is at y = 180; extending down 120 reaches the bottom exactly.

Writing two bars by hand is manageable; writing 100 is tedious. With D3, you supply the data and it generates the elements.

Here is the rendered output of that hand-written SVG: two ordinary bars, with no library involved:


🚀 Install D3

This course uses Node.js v22.0.0 and D3 7.9.0. In a Vue 3 project created with Vite, run:

npm install d3
An outdated Node.js version may cause installation to fail. Check your version with node -v; an LTS release is recommended.

Import D3 in your code:

import * as d3 from 'd3';

This imports all D3 utilities, including selections, scales, and transitions. It is a convenient approach while learning.


🛠 Your first chart

Our goal is to turn the five values [120, 200, 150, 80, 70] into five bars of different heights.

views/FirstChart.vue
<template>
    <svg ref="svgRef" class="chart"></svg>
</template>

<script setup>
import { onMounted, ref } from 'vue';
import * as d3 from 'd3';

const svgRef = ref(null);

const data = [120, 200, 150, 80, 70];

onMounted(() => {
    // 1. Select the SVG container
    const svg = d3.select(svgRef.value);

    // 2. Bind the data and create one rect per value
    svg.selectAll('rect')
        .data(data)
        .enter()
        .append('rect')
        .attr('x', (d, i) => i * 60) // Position bars at 60px intervals
        .attr('y', d => 300 - d) // Bar top = drawing height - value
        .attr('width', 40)
        .attr('height', d => d) // Bar height equals the value
        .attr('fill', '#5470c6');
});
</script>

<style scoped>
.chart {
    width: 100%;
    height: 300px;
}
</style>

In each callback, d is the current datum and i is its zero-based index. Substituting all five values shows exactly what D3 calculates:

Datum dIndex ix = i × 60y = 300 − dheight = d
12000180120
200160100200
1502120150150
80318022080
70424023070

The first row gives x=0, y=180, width=40, height=120, exactly matching our first hand-written rect. D3 simply automates these repeated calculations.

Here is the rendered output of this code:

Now focus on the core chain:

svg.selectAll('rect') // Select all rect elements (none exist yet)
    .data(data) // Bind five values
    .enter() // Get placeholders for data without elements
    .append('rect'); // Create one rect for each unmatched datum

Imagine handing out books: the data consists of five books, but there are no students (rect elements) yet. We need to add students so that each book has a recipient. That is what enter().append('rect') does: one student (bar) for each book (datum).

The .selectAll().data().enter().append() pattern is a foundation for almost every D3 graphic. We will examine it in detail next.

Two common pitfalls:
  1. Run drawing code in onMounted, when svgRef.value actually points to a DOM element.
  2. Give the SVG container a height. A height of 0 produces no visible chart, even though the code runs without errors. :::

❓ Questions and answers

Q1: Does D3 cost anything?No. D3 is open source under a BSD license and is free for personal and commercial use.Q2: Does D3 only work with SVG?No. D3 can also work with Canvas and ordinary HTML elements. SVG suits most charts, so this course uses it throughout.Q3: Why use D3 if I can write SVG by hand?Hand-written SVG works for fixed data. In real projects, data comes from APIs and changes over time; rewriting 100 elements for every update is impractical. D3 lets graphics update automatically with the data.Q4: Does import * as d3 increase bundle size?Importing everything can produce a larger bundle. It is convenient while learning, but production projects can import only the required modules, such as d3-selection and d3-scale, to reduce size.

🧪 Exercise

Modify the first chart above:
  1. Replace the data with seven days of sales figures. Choose your own values.
  2. Change the bar color to #91cc75.
  3. Following the table above, calculate each bar's x, y, and height on paper or in the console, then compare them with the rendered chart.
views/WeekChart.vue
<template>
    <svg ref="svgRef" class="chart"></svg>
</template>

<script setup>
import { onMounted, ref } from 'vue';
import * as d3 from 'd3';

const svgRef = ref(null);

onMounted(() => {
    const svg = d3.select(svgRef.value);

    // Write your code here
});
</script>

<style scoped>
.chart {
    width: 100%;
    height: 300px;
}
</style>

🎉 You have drawn your first D3 chart! Next, we will explore the full book-distribution analogy and learn how to add and remove graphics as data grows or shrinks.