惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

F
Full Disclosure
WordPress大学
WordPress大学
小众软件
小众软件
Cloudbric
Cloudbric
AWS News Blog
AWS News Blog
腾讯CDC
量子位
人人都是产品经理
人人都是产品经理
大猫的无限游戏
大猫的无限游戏
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
V
Vulnerabilities – Threatpost
Scott Helme
Scott Helme
Hugging Face - Blog
Hugging Face - Blog
博客园_首页
C
CXSECURITY Database RSS Feed - CXSecurity.com
The Hacker News
The Hacker News
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
IT之家
IT之家
Jina AI
Jina AI
Attack and Defense Labs
Attack and Defense Labs
S
SegmentFault 最新的问题
Simon Willison's Weblog
Simon Willison's Weblog
The Cloudflare Blog
阮一峰的网络日志
阮一峰的网络日志
T
Tailwind CSS Blog
Last Week in AI
Last Week in AI
博客园 - 【当耐特】
Google Online Security Blog
Google Online Security Blog
美团技术团队
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
V
Visual Studio Blog
罗磊的独立博客
L
LINUX DO - 最新话题
博客园 - Franky
博客园 - 叶小钗
Apple Machine Learning Research
Apple Machine Learning Research
The Last Watchdog
The Last Watchdog
J
Java Code Geeks
AI
AI
C
Cisco Blogs
酷 壳 – CoolShell
酷 壳 – CoolShell
C
Cyber Attacks, Cyber Crime and Cyber Security
Cisco Talos Blog
Cisco Talos Blog
博客园 - 三生石上(FineUI控件)
雷峰网
雷峰网
Help Net Security
Help Net Security
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
云风的 BLOG
云风的 BLOG
I
Intezer
S
Securelist

Home on Alex Plescan

Just for fun: animating a mosaic of 90s GIFs Two computers, one monitor, zero fiddling Placeholder names should be bad and unique Rebuilding this site Okay, I really like WezTerm GNU Parallel, where have you been all my life? Timeseries with PostgreSQL Using Declarative Shadow DOM to embed HTML emails on a web page Selling SaaS on Gumroad PDF: The Conjoined Triangles of Success Deploying Metabase to Fly.io The ".x" Files Xcode 8 managed signing: adding new device UUIDs to a provisioning profile Emojify your Wi-Fi (Netgear R6300 edition) How to use the San Francisco Mono typeface before macOS Sierra is released Disabling App Transport Security in your development environment Swift: A nicer way to tell if your app is running in Debug mode Development environment config overrides in Jekyll Setting up SwiftLint on Travis CI
Easy SVG sparklines
2023-07-08 · via Home on Alex Plescan

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:

a screenshot showing an example of a sparkline

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:

<svg height="180px" width="500px">
  <path
    d="M 0 14 L 1 15 L 2 10 L 3 11 L 4 7 L 5 5 L 6 0 L 7 5 L 8 10 L 9 11"
    stroke-width="2"
    stroke="red"
    fill="transparent"
  />
</svg>

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).

<svg height="180px" width="500px" viewBox="0 0 9 15">
  <path
    d="M 0 14 L 1 15 L 2 10 L 3 11 L 4 7 L 5 5 L 6 0 L 7 5 L 8 10 L 9 11"
    stroke-width="2"
    stroke="red"
    fill="transparent"
  />
</svg>

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 the vector-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 the svg element by setting preserveAspectRatio to none (docs).
<svg height="180px" width="500px" viewBox="0 0 9 15" preserveAspectRatio="none">
  <path
    d="M 0 14 L 1 15 L 2 10 L 3 11 L 4 7 L 5 5 L 6 0 L 7 5 L 8 10 L 9 11"
    stroke-width="2"
    stroke="red"
    fill="transparent"
    vector-effect="non-scaling-stroke"
  />
</svg>

That’s better, now for some more… flare… let’s add a fill to the SVG as well:

Adding a fill

To do this, we copy our existing line but set a fill on it instead of a stroke:

<svg height="180px" width="500px" viewBox="0 0 9 15" preserveAspectRatio="none">
  <path
    d="M 0 14 L 1 15 L 2 10 L 3 11 L 4 7 L 5 5 L 6 0 L 7 5 L 8 10 L 9 11"
    stroke="transparent"
    fill="pink"
  />
  <path
    d="M 0 14 L 1 15 L 2 10 L 3 11 L 4 7 L 5 5 L 6 0 L 7 5 L 8 10 L 9 11"
    stroke-width="2"
    stroke="red"
    fill="transparent"
    vector-effect="non-scaling-stroke"
  />
</svg>

Almost there! Let’s close that unsightly white gap. To do so, we need to extend our line to the bottom right of the graphic (L 9 15), then to the bottom left (L 0 15), then back up to the starting point (Z).

This creates a closed line that nicely encapsulates the area we want to fill in:

<svg height="180px" width="500px" viewBox="0 0 9 15" preserveAspectRatio="none">
  <path
    d="M 0 14 L 1 15 L 2 10 L 3 11 L 4 7 L 5 5 L 6 0 L 7 5 L 8 10 L 9 11 L 9 15 L 0 15 Z"
    stroke="transparent"
    fill="pink"
  />
  <path
    d="M 0 14 L 1 15 L 2 10 L 3 11 L 4 7 L 5 5 L 6 0 L 7 5 L 8 10 L 9 11"
    stroke-width="2"
    stroke="red"
    fill="transparent"
    vector-effect="non-scaling-stroke"
  />
</svg>

That’s looking pretty good now - especially considering how simple it was to draw. Now let’s move on to rendering these on the server…

Rendering Sparklines on the server

One of my favourite things about creating sparklines like this is that I can create the SVGs entirely on the backend. I don’t need to worry about using a JavaScript charting library, or sending the “points” data to the frontend. The browser requests an SVG. The server returns it. Simple!

Mailgrip is written in Elixir and uses the Phoenix framework, so the code I’m sharing is in Elixir too - but this approach could be adapted to any programming language.

The Phoenix controller defines a route that looks like:

defmodule MailgripWeb.InboxController do
  def activity_svg(conn, _params) do
    points =
      Emails.message_stats(conn.assigns.inbox, 30)
      |> Enum.map(fn stat -> Map.fetch!(stat, :count) end)

    conn
    |> put_resp_content_type("image/svg+xml")
    |> send_resp(200, MailgripWeb.Sparkline.draw(100, 20, points))
  end
end

Which in turn calls this module (heavily inspired by the ContEx package):

defmodule MailgripWeb.Sparkline do
  @fill "#dcfce7"
  @stroke "#bbf7d0"
  @stroke_width 4

  def draw(width, height, points) do
    vb_width = length(points) - 1
    vb_height = Enum.max(points)

    """
    <svg height="#{height}" width="#{width}" viewBox="0 0 #{vb_width} #{vb_height}" preserveAspectRatio="none" role="img" xmlns="http://www.w3.org/2000/svg">
      <path d="#{closed_path(points, vb_width, vb_height)}" stroke="transparent" fill="#{@fill}" />
      <path d="#{path(points, vb_width, vb_height)}" stroke-width="#{@stroke_width}" vector-effect="non-scaling-stroke" stroke="#{@stroke}" fill="transparent" />
    </svg>
    """
  end

  defp path(points, vb_width, vb_height) do
    [
      "M",
      points
      |> Enum.with_index()
      |> Enum.map(fn {value, i} ->
        x = i
        y = vb_height - value
        "#{x} #{y}#{if i < vb_width, do: " L "}"
      end)
    ]
  end

  defp closed_path(points, vb_width, vb_height) do
    [path(points, vb_width, vb_height), " L #{vb_width} #{vb_height} L 0 #{vb_height} Z"]
  end
end

That’s all it takes for minimal sparklines to add some flourish to your user interfaces!

My use of sparklines is gonna go:


Edit 15 July 2023: See Timeseries with PostgreSQL for an addendum re. how the timeseries data is generated.