Your First Charts

A chart is really just shapes placed in the right spots. In this chapter we take the small dataset on the left and turn it into our first charts.

1. The SVG canvas

Everything we draw lives on an SVG - a canvas you write with tags, the same building blocks as a web page. A tag is a keyword in angle brackets like <svg>, and most come in pairs: an opening <svg> and a closing </svg>.

An SVG canvas
<svg class="chart" width="600" height="400"></svg>

The SVG element can have fields of "width" and "height" which specify the dimensions of the SVG in pixels. class="chart" tells it to apply the styling for chart to the SVG (in our case just a black border)

(0, 0)(400, 250)

The coordinate system: Every position is measured from the top-left corner, (0, 0). x grows to the right, and y grows downward - so a bigger y sits lower on the canvas, the opposite of a maths graph.

2. Plotting Points with Circles

Now we draw inside the canvas. A point is a <circle>, which needs a centre (cx, cy) and a radius r:

A circle
<svg class="chart" width="500" height="350">
	<circle cx="50" cy={350 - 70} r="8" fill="steelblue" />
</svg>

To draw the circle:

  • We start with placing the circle at the correct position with cx and cy and then
  • r - gives it a radius.
  • fill to make it visible. This can be any colour eg. “red”, “#ff0000”, hsl(0, 100%, 50%), etc.
edit src/exercises/1-first-scatter-plot.svelte

3. Bars and Rectangles

A bar is a <rect> — a rectangle. It needs a position (x, y) for its top-left corner, plus a width and height:

A rectangle
	<rect x="30" y="280" width="40" height="70" fill="seagreen" />
  • x, y: Start by placing the top-left corner of the rectangle.
  • width and height set its size in pixels.
  • fill colours it in; stroke and stroke-width add a border, just like a circle.

Because y is the top edge, a bar resting on the floor has to start at y={350 - barHeight} and have a height of barHeight.

edit src/exercises/2-first-bar.svelte

4. Area Charts

A <path> can draw any shape. Everything lives in one attribute, d - a list of drawing commands the pen follows:

A path
<path d="M 50 280 L 160 50 L 260 170 Z" fill="steelblue" />
  • M x y moves the pen to a start point (without drawing).
  • L x y draws a straight line to a point.
  • Z closes the shape, joining the last point back to the start.

These strings get long and unreadable pretty fast, so in practice we almost never write d by hand - libraries like D3 generate it for us. We’ll build a short one here just to see how the pen moves.

edit src/exercises/3-area-chart.svelte