Skip to content
Tutorials Center
My learning

Topics

Lesson 3 of 44 ยท Getting Started

SVG Fundamentals for D3

Learn the SVG you need for D3: coordinate system, rect, circle, line, path and text, groups and transforms, the viewBox and the margin convention for charts.

D3 draws mostly with SVG, so a few SVG facts will save you hours. Most "D3 bugs" turn out to be SVG rules: the y axis points down, text needs text-anchor, and shapes inside a <g> are shifted by the group's transform. This lesson covers just enough SVG to chart confidently.

The coordinate system

An SVG canvas has its origin (0, 0) at the top-left corner. x grows to the right and y grows downward. This is the opposite of a math graph, which is why a bar chart needs y = height - barHeight and why D3 scales for the vertical axis usually have a range like [height, 0].

flowchart TB
  O["(0,0) top-left"] --> X["x grows right"]
  O --> Y["y grows down"]

The y axis is flipped compared to a math graph.

The basic shapes

Element Main attributes
<rect> x, y, width, height, rx, ry (rounded corners)
<circle> cx, cy, r
<ellipse> cx, cy, rx, ry
<line> x1, y1, x2, y2
<polyline>, <polygon> points="x,y x,y ..."
<path> d (a mini-language for any outline, see Paths and Links)
<text> x, y, text-anchor, dominant-baseline, font-size

Colors come from presentation attributes or CSS: fill (inside), stroke (outline), stroke-width, opacity, fill-opacity. A shape has fill="black" by default, and a line has no stroke by default, so a <line> without stroke is invisible. That surprises almost everyone once.

Every basic shape

Text alignment

SVG text is positioned by a baseline point. x and y mark where the text starts and where its baseline sits. Two attributes make centering easy:

  • text-anchor: start (default), middle or end, which aligns horizontally around x.
  • dominant-baseline (or dy="0.35em"): middle or hanging aligns vertically around y.

D3's axis code uses dy="0.71em" and dy="0.32em" so labels sit neatly next to ticks. You will use the same trick.

Groups and transforms

<g> groups elements. A group has no size of its own, but whatever you set on it applies to all children: fill, stroke, class, and especially transform.

HTML
<g transform="translate(60, 20)">
  <rect width="40" height="40" />
</g>

The common transforms are translate(x, y), scale(k), rotate(deg, cx, cy). Transforms apply right to left in a list, and children use the group's coordinate system, so inside the translate(60, 20) group above, x=0 is really x=60 on the page. D3 charts rely on this: you place the plotting area once, and draw everything in local coordinates.

Groups move everything inside

The margin convention

Charts need room for axis labels, so D3 users keep a margin object and draw into an inner area. This pattern appears in almost every D3 chart:

JavaScript
const margin = { top: 20, right: 20, bottom: 30, left: 40 };
const width = 420, height = 240;
const innerWidth = width - margin.left - margin.right;
const innerHeight = height - margin.top - margin.bottom;

const svg = d3.select("#chart").append("svg")
  .attr("width", width).attr("height", height);

const g = svg.append("g")
  .attr("transform", `translate(${margin.left},${margin.top})`);

Scales then use [0, innerWidth] and [innerHeight, 0] as ranges, and everything is appended to g. Axes live in the margins because they sit outside the inner box.

Responsive SVG with viewBox

Instead of fixed pixel sizes, give the SVG a viewBox. It defines an internal coordinate space (minX minY width height) that the browser scales to fit the element, preserving aspect ratio. Drop the width and height attributes and use CSS (width: 100%; height: auto).

viewBox scales the whole drawing

The drawing is always laid out in 400 by 200 units and the browser scales it. This is the simplest way to make a chart responsive, though text scales too. For charts whose labels must keep a fixed pixel size, re-render on resize instead (chapter 8 shows how).

In D3 the namespace matters. d3.select("svg").append("rect") works because D3 creates SVG elements in the SVG namespace automatically when the parent is SVG. Writing document.createElement("rect") yourself would create an unknown HTML element that never renders.

Layering and order

SVG has no z-index. Elements are drawn in document order, so later elements are on top. To bring something to the front, re-append it, or use D3's selection.raise(). Plan your layers: gridlines first, then data shapes, then labels.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Where is the SVG origin (0, 0), and which way does y grow?

    SVG puts (0, 0) at the top-left with y increasing downward, so vertical D3 scales usually use [height, 0].
  2. 2. Why does a <line> element with no stroke attribute look invisible?

    The default stroke is none. A line has no interior, so you must set stroke (and optionally stroke-width).
  3. 3. What does <g transform="translate(40, 30)"> do to a child <rect x="0" y="0">?

    Children are drawn in the group's local coordinate system, so the rect appears at (40, 30) on the page.
  4. 4. What is the benefit of a viewBox?

    With viewBox (and no fixed width/height), the drawing scales to its container, keeping the aspect ratio.

Summary

  • SVG's origin is top-left and y points down; flip vertical scales accordingly.
  • Basic shapes (rect, circle, line, polyline, polygon, path, text) are styled with fill and stroke.
  • <g> groups elements and transform="translate(...)" moves them together; later elements paint on top.
  • The margin convention places an inner g so axes have room, and viewBox makes drawings scale.

Next: Loading and Parsing Data