Drawing charts with SVG

Advanced

Introduction

Chart libraries such as D3, Vega-Lite, Chart.js and Plotly mostly draw with SVG, a text format for shapes that browsers display crisply at any size. Building a simple chart by hand shows what those libraries do: map data to pixel positions, then write shapes. It also makes it possible to create a tiny chart with no library at all, as this site's own visualizer does.

How it works

Coordinates. An SVG starts with <svg viewBox="0 0 120 60">: a drawing area 120 units wide and 60 high. The origin (0, 0) is the top left, x grows to the right and y grows downwards, the opposite of a chart's y axis. So a data value must be flipped: high values get small y.

Scales. A scale function maps a data value to a position. For the y axis, with a plot area from pad to height − pad:

def y_scale(v):
    return height - pad - (v - vmin) / (vmax - vmin) * (height - 2 * pad)

The smallest value lands at the bottom of the plot area and the largest at the top. The x scale is the same idea without the flip. For a bar chart, bars start at zero, so vmin is 0, and each bar gets a slot of width (width − 2 × pad) ÷ n, with a little space between bars.

Shapes.

  • <rect x y width height/> draws a bar: x and y are its top-left corner, so a bar's y is the bottom minus its height.
  • <line x1 y1 x2 y2/> draws axes and grid lines.
  • <polyline points="x1,y1 x2,y2 ..."/> draws a line chart through the scaled points, with fill="none" and a stroke colour.
  • <text x y>label</text> writes labels; text-anchor="end" right-aligns them.

Accessibility. Give the SVG a <title> and role="img" with an aria-label describing the finding, and keep the key numbers in nearby text, because a screen reader cannot read a picture.

Why learn it. When a library's chart looks wrong, the cause is almost always a scale (wrong domain, forgotten flip, zero missing) or an element attribute. Reading the SVG it produced makes such problems easy to find.

Example

# Building an SVG bar chart by hand: scale values to pixels and flip the y axis.
values = [4, 9, 6]
width, height, pad = 120, 60, 5
top = max(values)
slot = (width - 2 * pad) / len(values)
print(f'<svg viewBox="0 0 {width} {height}">')
for i, v in enumerate(values):
    h = v / top * (height - 2 * pad)
    x = pad + i * slot + 2
    y = height - pad - h
    print(f'  <rect x="{x:g}" y="{y:g}" width="{slot - 4:g}" height="{h:g}"/>')
print("</svg>")
Open in compiler

Line by line

  1. The drawing is 120 by 60 units with 5 units of padding.
  2. Each bar's height is its share of the largest value times the plot height.
  3. Its y is the bottom of the plot area minus its height, which flips the axis.
  4. Each bar sits in its own slot, inset by 2 units on each side for spacing.

Expected result

<svg viewBox="0 0 120 60">
  <rect x="7" y="32.7778" width="32.6667" height="22.2222"/>
  <rect x="43.6667" y="5" width="32.6667" height="50"/>
  <rect x="80.3333" y="21.6667" width="32.6667" height="33.3333"/>
</svg>

In the real world

D3 is built around scale functions exactly like y_scale, and frameworks render charts as SVG elements. News sites hand-tune SVG charts for print and web, and design systems ship small SVG sparklines in tables and cards.

Common mistakes

  • Forgetting that y grows downwards, which draws charts upside down.
  • Using the data minimum as the bottom of a bar chart instead of zero.
  • Dividing by zero when all values are equal (max = min); place the line in the middle instead.
  • Leaving no padding, so axis labels are cut off.

Best practices

  • Write scale functions once and use them for every element.
  • Keep a fixed viewBox and let CSS size the SVG.
  • Add a title and an aria-label that state the chart's point.

Summary

SVG draws shapes in a coordinate system whose y axis points down. Scale functions map data to pixels, flipping y and leaving padding; rect elements make bars, polyline makes lines, and text adds labels. Libraries do exactly this, so knowing it makes their output understandable.

Quick check

1. In SVG, where is the point (0, 0)?
2. With height 100 and no padding, where does the maximum value of a 0-to-max scale go?
3. Which element draws a line chart through many points?
4. A bar of height 30 must stand on a baseline at y = 90. What is its y attribute?

Key takeaways

  • In SVG, y grows downwards, so data values must be flipped: y = bottom − scaled value.
  • A linear scale maps the data range onto the plot area: start + (v − min) ÷ (max − min) × size.
  • Every chart library builds these same elements; knowing them makes charts debuggable and customisable.

Practice problems for this lesson

My notes

Write down what you want to remember from this lesson. Notes are saved on this device as you type, and appear on your dashboard.