Welcome to my blog. I do my utmost to make my code transparent and easy to understand. Send me an email with feedback!

←Return Home

Sparklines with D3.js

I still remember picking up Edward Tufte's book, "The Visual Display of Quantitative Information", for the first time. Its pages oversized and crisp, I flipped through and studied each chart in meticulous detail. Sure, Tufte's appeal to minimal "paint", clean lines and clear labels was a rewarding educational experience. But I also enjoyed some of the stranger charts that were mentioned in that book; most notably, sparklines.

Sparklines are a simple idea (in hindsight) but they felt revolutionary to me at the time. They are just miniature charts, embedded in the text of a paragraph. If a journalist were to write about a stock, say, and had limited space in which to write her words, she could throw in a sparkline to show AAPL's stock over time, and only occupy about 1/4 of a line of text. Sparklines are a way to show information quickly, in a compartmentalized manner, and save text. I suppose that I'm drawn to sparklines because they feel like worthy companions for a journalist who wants to quickly convey a point at a deeper level of detail than the space requirements of a typical newspaper might allow.

The purpose of this blog is simple: Make a few sparklines, and embed them in the words on this page. For this post, I learned about Sparklines from this article, adapted the code, and reconstructed them with D3.js. All of the sparklines on this page were built with version 6 of the D3 library, so the code is up-to-date. All of the code that was used to generate this blog post can also be viewed on my CodePen.

Let's start with the simplest sparkline: an inline line chart. This chart is embedded right in the text, like magic. Beautiful! Notice, too, that this sparkline doesn't push the surrounding lines of text up or down; it's height exactly matches that of the paragraph's spacing. I went into the CSS for this blog page, noticed that the line spacing is set to 25px, and so set the height of this sparkline to 20px + 5px margin on the top. The second quirk, to get it to display properly, is to set its display property to inline-block.

On to the next one: a simple bar chart. The approach to make this follows the same logic as the line chart. The only difference, in this case, is that I'm using real data; namely, the frequency with which each letter in the English alphabet is used. You can view a bigger version of this chart on my Observable page.

Okay, let's do one more chart; a bar chart, again, but with both positive and negative values. You could use this type of chart to show gains or losses of a stock over time, for example.

Hope you enjoyed this post!

←Return Home