Sparkline charts are compact, simple charts showing a general trend without getting into the nitty-gritty of a more complete solution.
On Mailgrip, I use them as a UI flourish to give a visual indication of how many emails an inbox has received over time:

This post will explain how to use SVG to create minimal sparklines in a really easy and fast way.
Hand crafting the SVG
Let’s start by writing the SVG by hand, and then I’ll show you an example of the Elixir code I use to generate sparklines in Mailgrip.
Say we’ve got this series of 10 data points to display:
1, 0, 5, 4, 8, 10, 15, 10, 5, 4
Drawing a line
Everything has a starting point, including our sparkline. So let’s begin by drawing a line.
SVGs use a set of primitive commands (docs) to draw shapes. The ones we’re interested in are:
- M (
moveto
): Sets a new starting point. It takes two parameters: X and Y. - L (
lineto
): Draws a line from the current position to a new one, specified by X and Y parameters. - Z (
closepath
): Draws a line from the current position back to the starting position.
We’ll use these commands to draw our lines based on X and Y coordinates.
In SVG, the origin coordinates (0, 0) are at the top left. However we want our chart’s coordinates to start at the bottom left.
To adjust the Y position for a point, we’ll substract it from the largest (max) point in our data set. This flips our Y positions to:
14, 15, 10, 11, 7, 5, 0, 5, 10, 11
Figuring out the X positions is straightforward; they’re just the index of the point we’re drawing:
0, 1, 2, 3, 4, 5, 6, 7, 8, 9
Now, let’s put these coordinates to work and draw our sparkline:
Behold our beautiful creation:
Okay that’s a bit sad, we’ve got a few more steps to go still…
Scaling
We’ve defined that our SVG should have a height of 180px and width of 500px, but the line we drew is rendering at one pixel per X/Y coordinate.
Here’s where SVG’s ability to Scale Vector Graphics really helps out. Instead of having to transpose our data to screen space coordinates, we can let SVG do it for us!
We use the viewBox
attribute (docs) on the SVG element to set the coordinate space of the chart. viewBox
values are zero-indexed, so our width will be 9
(because we have a total of 10 points) and our height will be 15
(because our max point value is 15).
Ah, but now a couple of other funky things have happened:
- The
stroke-width
of 2px has scaled up with the image. We can tell SVG to keep the stroke consistent by setting thevector-effect
(docs) property on our path. - The image scaled up using the aspect ratio of the 9 x 15
viewBox
, which is different to that of our image. We can tell SVG to maintain the aspect ratio of thesvg
element by settingpreserveAspectRatio
tonone
(docs).