© Alex Libby  2018
Alex LibbyBeginning SVGhttps://doi.org/10.1007/978-1-4842-3760-1_8

8. Creating SVG Charts

Alex Libby1 
(1)
Rugby, Warwickshire, UK
 

It goes without saying that SVG is, of course, a very visual technology – it lends itself to a multitude of different uses. One great use though is through the creation of charts; yes, it’s hard to believe, but it is a perfect tool for this purpose! We can take it even further though, by animating said chart content – with a little care, we can produce some really powerful content that is visually engaging for our visitors.

Throughout these pages, we’ll take a look at some of the techniques we can use to produce anything from simple pie charts through to more complex infographic solutions. To kick off our journey though, we should take a few moments to explore the answer to this question: What makes SVG such a great format for charting?

Understanding the Benefits of SVG for Charts

If we’re tasked with creating a chart, then there are several ways of skinning this problem – one might decide to use the HTML <canvas> element, or simply create it as an image and embed it into the page. Sure, these will work technically, but are they the best solution?

For one – if we create an image that then needs to be resized, we can’t simply change the dimensions in code; chances are the image will lose its sharpness. Making use of the canvas element isn’t much better either; we might be able to resize the element in code, but we lose the ability to interact and have to create extra code, to manage fallback and accessibility (canvas elements are not part of the DOM). Ouch…yes, there may be plug-ins available to help ease the process, but do we really need to introduce yet another plug-in?

As a format, SVG is perfect for charting – we’ve already seen how well it works for images or icons, where it offers us several benefits:
  • Small file sizes that compress well;

  • Scales to any size without losing clarity (except very tiny sizes);

  • Looks great on retina displays;

  • Design control like interactivity and filters.

We can add a couple of extra benefits to this list, if we use SVG to create our charts:
  • SVGs are accessible to screen readers (with a little bit of work);

  • There are plenty of SVG-based chart frameworks out there to help with creating charts;

  • There are a number of online sites available that can help with creating prototypes online, such as the online editor of AMCharts ( https://live.amcharts.com/ ) or Method Draw ( http://editor.method.ac/ )

We could just work with the simplest option for adding charts to our pages – create it in Illustrator, then embed it as an SVG using <img> tags in our code.

It’s a valid option, but one where we miss out on so many benefits – not only will it be inaccessible to screen readers, we also lose the ability to interact with the chart, using a mouse or keyboard. This is clearly not great as a customer experience – there is something to be said for being able to select a segment in a pie chart to show data, or even just be able to hover over that segment and have it change color!

To really make the most of SVG, we need to bring the code inline – we can style it using CSS, make it fully interactive using JavaScript, and retain all the benefits of accessibility at the same time.

There are two routes we can use to creating SVG-based charts, without having to resort to applications such as Illustrator; we can craft them by hand or use an online service such as AMCharts to experiment before exporting the code for use in our project. We’ll take a look at the latter option a little later in this chapter, but for now, let’s crack on with creating some charts by hand, so we can get a feel for what is involved.

Designing Individual Charts Using SVG

I don’t know about you, but I’m one of those people where the phrase “spoilt for choice” can be a double-edged sword! We may only have a select few different types of chart available to us, but each allows a variety of different designs, depending on how we configure each chart.

Over the course of this chapter, we will examine examples of some of the more popular chart types. Each of the charts use elements we’ve already seen from earlier in the book, so it should not come as too much of a surprise in the demos. Let’s start that journey, with a look at creating donuts.

Creating Donuts

If someone were to ask me how I would create a donut, you might be forgiven for thinking they were referring to food – in this case, we’re clearly thinking of something else!

Leaving aside any analogy to foodstuffs, donut charts are very easy to create – the key is the <circle> element; one might be used to create a background ring, with another displaying the visual representation of our statistic. We’ve already been introduced to this element, so much of the code in the upcoming demo should come as no surprise to us. To see what I mean, let’s dive in and take a look at what is involved to set up our example donut chart.

CREATING A DONUT CHART

We’ll start by setting up the basic code files:
  1. 1.

    We’ll begin with extracting a copy of the donut folder from the code download that accompanies this book; save this to the root of our project folder.

     
  2. 2.
    Next, go ahead and open donut.html – we will add in the markup to create our chart. This will come in three parts, beginning with adding the SVG container immediately after the <h2> tag in our code:
      <svg x="0px" y="0px" width="340px" height="333px" viewBox="0 0 340 333">
      </svg>
     
  3. 3.
    Next, add in the following definition code immediately below the opening <svg> tag – this is what we will use to style our donut gauge:
        <defs>
          <linearGradient id="gradient">
            <stop stop-color="#2f4f4f" offset="0%"></stop>
            <stop stop-color="#bbd6d6" offset="100%"></stop>
          </linearGradient>
        </defs>
     
  4. 4.
    We now need to add in the all-important markup for our donut – go ahead and add in the following below the closing </defs> tag, leaving a blank line in between:
        <g transform="translate(115, 115)">
          <circle r="70" class="circle-back" />
          <circle r="70" class="circle-front" transform="rotate(270.1)" />
          <text x="-30" y="10">25%</text>
        </g>
     

A finished version of this demo is available in the code download as donut – finished version.html, in case you need a reference!

  1. 5.

    Go ahead and save the code – if all is well, we should see something akin to the screenshot shown in Figure 8-1.

     
../images/461821_1_En_8_Chapter/461821_1_En_8_Fig1_HTML.jpg
Figure 8-1

Creating our donut chart

Ah – the sweet smell of success…granted, I can’t help but think of that typical sweet delicacy, but I must refrain for now; our demo has created a great way to illustrate results in a more interesting format than a simple bar or line chart. There are several good use cases for this chart type, so without further ado, let’s dive in and see how our code works in more detail.

Understanding How Our Chart Works

This is a relatively simple chart to create – the crux of it relies on using two <circle> elements to create the back and front circles seen in Figure 8-1. Our code starts with creating a typical SVG container of 340px by 333px, limited by a viewBox of the same size.

We then create a definition for our linear gradient, which is called (unsurprisingly!) gradient . This is set to a very dark cyan color and ends with a grayish tone of the same color. This gradient is then use in our front circle – both elements are set to a radius of 70, with the gradient effect applied using the .circle-front class. The demo is then topped off with a single <text> element that provides the 25% displayed within the two circles.

Now – there is a key point we should be aware of: the presence of the two transform statements. The first one, applied to the <g> tag, merely slides the circles into view – without it, the chart would appear off center, with most of it hidden. The second one is more critical: SVG charts of this type usually start at the three o’clock position, which isn’t so intuitive for the user. To correct this, we simply rotate the front circle anti-clockwise by 90 degrees, so it becomes more recognizable as a chart.

However, this isn’t where the real magic happens – that is in how we calculate how much of the gauge should be displayed. There is a little formula we can use for this purpose; let’s take a moment to explore this in detail.

Working Through the Formula

Unfortunately, with this type of chart (and others too), we have a little calculating to do – we’ve displayed both circles on screen, but how do we calculate how much of the front circle should show?

Well – rest assured, the math required is a relatively straightforward two-step process. The first step is to work out the circumference of our circle – we can calculate that with a simple formula:
2 x π x radius
So – to translate that into figures we have this:
2 x 3.14 x 100, or 628.

Now – question is: Where did the 100 come from? Well in this case, we will use 100% as our circumference; the calculation is unit agnostic, hence just using the value 100, and giving us a value of 628, or 628px (or 39.25rem, as shown in the demo).

The next part gets a little more complicated – we now need to work out how much of the darker-colored ring to display. To get the value, we can use this formula: C x (1 – 0.25), where 0.25 represents 25% or the one-quarter-filled value of our ring chart. When calculated, we get 471px (or 29.4375rem, as shown in the demo); this part is offset, leaving us with 157px (9.875rem) or 25% of our circumference.

As an aside, you may ask why we’re not using 70 as value for radius – after all, this is what is specified in the original markup, right? Well, there is a good reason for this – it simplifies the math involved, both for working out the circumference (which will always be 628px), and the values for stroke-dasharray and stroke-dashoffset: anything to make our lives easier! If you want to dive into the detail, Mark Caron has an extensive article on Medium, which explains the calculations; it’s available at https://medium.com/@heyoka/scratch-made-svg-donut-pie-charts-in-html5-2c587e935d72 .

Putting It into Practice

Armed with our newfound knowledge – let’s put this into practice: take a look at the CSS style sheet for the donut demo, starting with the style rule for .circle-back.

We have two values present – one is stroke-fill, which is self-explanatory (it fills our circle with a light gray color). The second, stroke-width, needs more explaining: this is the width of the border of our circle. Normally we would set this fairly thinly, but here’s the rub: when making the border thicker, it actually has the effect of drawing fully filled-in circles! Try adjusting the value using a browser’s console, and you’ll soon see what I mean…

Moving on, we have the .circle-front rule; this uses a slightly narrower stroke-width value, to give the effect of a border inside and outside of our grayish-color gradient effect. But – and here comes the tricky part: the use of stroke-dasharray . This property controls the pattern of dashes and gaps used on stroke paths; setting this at 629px effectively fills up our stroke completely. (If the value had been set low, to say 50px, then you will start to see the effects of this property.)

Now – remember the 471px value from earlier in this demo? Here, we use it to set the stroke-dashoffset value; this simply specifies how far in to start the dash pattern specified by stroke-dasharray.

But – there is a sting in this tale: the stroke-dashoffset value works anti-clockwise, whereas stroke-dasharray works clockwise, but starts on the right, at the 3 o’clock position. This can mean that if you were to produce a circle that had a dotted/dashed border effect, you might not get the effect you were expecting; to fix it, we can specify a value of 25 (or 25%) to reset the starting point of this effect to the top dead center of our circle. Note though – this 25% is not a negative number, as stroke-dashoffset works counter-clockwise, not clockwise.

To really understand how these properties work, I would recommend taking a look online; Mozilla Developer Network (MDN) provides some useful resources:

Now that we’ve covered how to create our segment effect, let’s take a look at a similar type of chart – the typical pie chart. No, I’m not thinking of visiting the local bakery (although it’s a tempting prospect!), but a more in-depth chart with multiple segments. It uses similar properties to our completed donut chart, so let’s dive in and take a look in more detail.

Eating Pie

I don’t know about you, but for some bizarre reason, the title of this chapter reminds me of that sci-fi flick, Men in Black, with Will Smith’s character who has something of a real penchant for eating pie! Our next example takes the form of a pie chart, such as the one shown in Figure 8-2, with varying segments representing our data:
../images/461821_1_En_8_Chapter/461821_1_En_8_Fig2_HTML.png
Figure 8-2

Our finished pie chart

Thankfully SVG lends itself well to creating pie charts, as it does for other chart types; there is some math involved, but it isn’t difficult. We’ll work through it shortly, but for now, let’s get on with creating our demo.

CREATING A PIE CHART

Okay – we’ll start with setting up our markup:
  1. 1.

    We’ll begin by extracting a copy of the pie folder and saving it to our project area.

     
  2. 2.

    Inside this folder, you will find a copy of pie.html, with a preconfigured <svg> container – go ahead and open it in your text editor.

     
  3. 3.
    We need to start adding our segments in – go ahead and add the first immediately after the opening <svg> tag:
          <g>
            <circle class="first" r="16" cx="31" cy="31" stroke-dasharray="43 100"></circle>
            <text x="75" y="-62" transform="rotate(90) scale(0.5)">Cherries</text>
          </g>
     
  4. 4.
    For the second segment, add this in a similar manner:
          <g>
            <circle class="second" r="16" cx="31" cy="31" stroke-dasharray="19 100" stroke-dashoffset="-43"></circle>
            <text x="43" y="-22" transform="rotate(90) scale(0.5)">Oranges</text>
          </g>
     
  5. 5.
    Segment number three is up next – go ahead and add this code in as before:
          <g>
            <circle class="third" r="16" cx="31" cy="31" stroke-dasharray="14 100" stroke-dashoffset="-62"></circle>
            <text x="7" y="-43" transform="rotate(90) scale(0.5)">Bananas</text>
          </g>
     
  6. 6.
    We’re almost done: the last segment needs to go in before the closing </svg> tag:
          <g>
            <circle class="fourth" r="16" cx="31" cy="31" stroke-dasharray="25 100" stroke-dashoffset="-76"></circle>
            <text x="12" y="-78" transform="rotate(90) scale(0.5)">Apples</text>
          </g>
     
  7. 7.

    Go ahead and save the file – if we preview it in a browser, we will see the chart indicated at the start of this exercise.

     

This chart uses many of the same properties that we saw back in the donut demo, but we take a different route to calculating the width of each segment. This one requires the use of the viewBox values, so without further ado, let’s dig in and find out how we arrived at the values used in this demo.

Exploring the Code in Detail

So – how does our pie chart work? And what’s the connection to the viewBox values in our demo...?

Well, there are several key parts to making this demo work – we begin with setting our radius value at 16px, before multiplying twice to arrive at each of the cx and cy values, then multiplying that figure twice to arrive at our viewBox size:
<svg viewBox="0 0 64 64" preserveAspectRatio="xMidYMid meet">
So, let’s take one of the four segments as an example:
  <g>
      <g>
        <circle class="fourth" r="16" cx="31" cy="31" stroke-dasharray="25 100" stroke-dashoffset="-76"></circle>
        <text x="12" y="-78" transform="rotate(90) scale(0.5)">Apples</text>
      </g>  </g>

Here, we set an initial radius (or r) value of 16 – this, along with the cx and cy values will remain constant throughout. Hold on a minute: doesn’t that mean we will have equal segments for our pie chart? Well, no – because we make use of a little trick at this point: let me introduce you to the stroke-dasharray property.

Put simply, the stroke-dasharray property is like a mask; it tells our SVG how much of our chart to show, and what proportion should be (effectively) hidden. Let’s work through a quick example, using the code we’ve just created in our previous demo.

In the code, the first item we’re counting is Cherries – let’s for argument’s sake say our total is 43. The stroke-dasharray property works on the basis that 43% of our chart will be visible. The 100 value is to ensure that we complete a full turn of the circle, even though it will be hidden, as shown in Figure 8-3.
../images/461821_1_En_8_Chapter/461821_1_En_8_Fig3_HTML.jpg
Figure 8-3

The first of our segments...

Seems straightforward, right? Well, it might – if only for one thing: stroke-dasharray works anti-clockwise, but starts from the 3 o’clock position, not 12. So how come our chart looks like it’s doing the opposite? Easy – our SVG has a transform() statement in the style sheet, to rotate it anti-clockwise by 90 degrees.

Okay – hopefully you’re still with me, as things are about to get interesting! Our chart has three more segments to add, so how are these added in, without each segment ending up being misplaced and clashing with each other?

The segments are set in a similar fashion to the first one, inasmuch as we have radius, cx, cy, and stroke-dasharray values. However, we have the presence of an additional property: stroke-dashoffset. This merely leaves a gap before we start applying stroke-dasharray; this has the effect here of bumping the segment round to the first available space after the previous segment. Let me explain with a quick walk-through:

We don’t need stroke-dashoffset on the first segment, as it is assumed this will be zero by default. Clearly though, we need something to position segments two, three, and four, so we set values for each of these. Assuming we have set our stroke-dasharray values in the same way as before (they are 19, 14, and 25), we simply subtract the stroke-dasharray value from the previous stroke-dashoffset value . Take a look at segment two for example – we set the stroke-dashoffset value to -43; subtracting 19 from this value will give the stroke-dashoffset value for our third segment.

Now – some of you at this point may ask why we are specifying negative values: it’s a perfectly reasonable question. The answer is simple: because stroke-dashoffset works anti-clockwise by default, we want our segments to run clockwise. Turning the number negative simply reverses the direction of travel!

It’s worth pointing out that you may well see lots of other people try to specify complex formulae to create pie charts; in reality, this isn’t necessary, as long as you can keep some of your initial sizes such as radius and viewBox as whole integers, and that you use percentage values where possible. It’s not obligatory, but I’m a great believer in the KISS principle: after all, why make life complicated when you don’t need to?

Okay – let’s move on: our next example chart puts us on the straight and narrow (so to speak). It’s time to take a look at the typical bar chart and see how we might implement it using SVG in more detail.

Raising the Bar

So far, we’ve created a couple of example charts that are circular – it’s time to put a different spin on things and go straight. Our third example is a more typical bar chart; it’s the kind you might see displayed within a poll.

For the purposes of our demo, we’ll keep it simple with listing some values that you might see in a poll that has just been launched – in this case, ours would be based around finding out what people use as their main technology of choice. Before we get stuck into our code, Figure 8-4 shows a screenshot of the finished article:
../images/461821_1_En_8_Chapter/461821_1_En_8_Fig4_HTML.jpg
Figure 8-4

An example bar chart

CREATING A BAR CHART

Let’s make a start on our code – all of the code text files mentioned in the steps are stored within the code subfolder:
  1. 1.

    We’ll start by extracting a copy of the bar folder from the code download that accompanies this book – go ahead and save it at the root of our project folder.

     
  2. 2.

    Next, go ahead and open a copy of bar.html – this contains the base markup, into which we will add the code for our chart.

     
  3. 3.

    The first block of code to add is in the x-axis.txt file – copy and paste this on or around line 10, immediately after the opening <g> tag on or around line 10.

     
  4. 4.

    The second block takes care of the y-axis of our chart – for this, go ahead and copy the code from y-axis.txt in to or around line 36 of our code, immediately after the closing </g> statement of the Create x-axis block.

     
  5. 5.

    We have one more block to add – this looks after the bars, labels and styling for our chart. For this, copy the contents of labels.txt into our markup – this should be on or around line 42, after the closing </g> tag from the points block in the previous step.

     
  6. 6.

    Save the file, then preview it in a browser – if all is well, we should see the chart displayed at the start of this exercise.

     

If we examine the results of the last exercise, we will see a fairly simple chart – it wouldn’t look out of place on a report, although it could use tweaks to add an x-axis label, for example!

That aside, if we take a look at the code – it looks scary, but in reality it is straightforward, and nothing that we’ve not already seen from earlier in the book. To understand what is involved, let’s dive into that code in more detail, and see what makes our bar chart tick.

Understanding Our Code

Take a look at that code – we can see it comes in three parts: the first takes care of the x-axis, the second the y-axis, and the third covers the bars in our chart.

You will notice that we use the <g> or group element to separate each block, or in some cases, sub-block – our first block takes care of drawing the x-axis, using the command <path d="M0,6V0H300V6"></path>, toward the bottom of this first block.

The real magic for this block though comes in the form of multiple sub-blocks, which take care of each of the drop ticks that populate this axis:
        <g class="tick" transform="translate(255.5,0)">
          <line y2="6" x2="0"></line>
        </g>

Here, we simply draw a single line from point 6 up to point zero – this is repeated multiple times in this first block, using the transform() command to leave a gap between each tick line.

Notice something about each tick line? We only have one set of coordinates, so what gives? The reason for this is that the starting x1 and y1 are assumed to be 0,0 by default, so there is no need to include them explicitly.

There is a simple trick we’ve used here to ensure the ticks are evenly spaced – the first one is positioned at (30.5,0), using the translate command. To arrive at this, we simply take half of the width of each bar (20.5), and add 10, to allow for the space between the y-axis and the edge of the bar. The subsequent ticks are spaced at 44-pixel gaps – this is the width of the bar, plus 3 to allow for a little gap between each bar.

Moving on, the second block performs a similar task – we use the <path> element at the bottom of this block to draw the y-axis. Each of the tick lines are drawn using the same principle as we did for the x-axis (not forgetting the default 0,0 value for each starting point). We use a <text> element this time to add in the percentage values – each text element is positioned using the dy, x, and y properties.

We then round out our demo with the third and final block – this takes care of each bar shown in our demo. There is nothing complicated here; we set the x and y values to locate each bar, then set height and width properties to control the size of each bar. In each case, the width is set to 41px wide; the height is merely the sample value that would have come from our poll. Each bar is complemented by a <text> element to display the name of each technology in question; each is rotated 90 degrees anti-clockwise to align them with the top left point of each bar.

Okay – let’s move on: there is one more chart type we should cover: line charts! This uses the same principles to create our axes that we used back when we created our bar chart example; this time though, we make use of the <path> statement to join the points of our line chart. Let’s take a look in more detail at how this works in practice.

Connecting the Dots

Charts come in all shapes and sizes, with some more suited than others to displaying certain types of information. For example, if you wanted to track the history of a share price, pie charts clearly wouldn’t work – this would be more suited to line charts.

As with other chart types, line charts use many of the same principles that we’ve already seen – we’d use <line> elements to draw our axes, with a <path> element to connect the reference points in our chart. Let’s take a look at one such example to see how this would work – in our next demo, we’re going to use example data that might indicate popularity of a certain browser over the course of five months – no prizes for guessing which heavyweight browser we’re using as the basis for our demo: it is Chrome!

CREATING A LINE CHART

Let’s make a start on our demo – all of the code text files mentioned in the steps are stored within the code subfolder, which you will find in the line folder in the code download:
  1. 1.

    We’ll start by extracting a copy of the line folder from the code download that accompanies this book – go ahead and save it at the root of our project folder.

     
  2. 2.

    Next, go ahead and open a copy of line.html – this contains the base markup, into which we will add the code for our chart.

     
  3. 3.

    The first block of code to add is in the grid.txt file – copy and paste this on or around line 10, immediately after the opening <svg> tag.

     
  4. 4.

    The second block takes care of the data points that are on the chart – for this, go ahead and copy the code from points.txt in to or around line 34 of our code, immediately after the two <use...> statements.

     
  5. 5.

    We have one more block to add – this looks after the labels for our chart. For this, copy the contents of labels.txt into our markup – this should be on or around line 42, after the closing </g> tag from the points block in the previous step.

     
  6. 6.

    Save the file, then preview it in a browser – if all is well, we should see the chart displayed in Figure 8-5.

     
../images/461821_1_En_8_Chapter/461821_1_En_8_Fig5_HTML.jpg
Figure 8-5

Creating a line chart

In our demo, we’ve produced a simple chart that illustrates the level of browser usage over the period of five months; in reality we would want to include mobile usage too, given how much it has exploded over the last few years! The simple design of our chart reveals a number of key techniques for creating this type of chart, so let’s dive in and take a look at our code in more detail.

Dissecting Our Code

In our demo, we’ve created a typical line chart – we’ve specified a number of points, which we connect using a filled-in block to simulate a line that we might otherwise have used. A look at the code might give the impression that it is a complex setup – in reality, it’s not difficult, as long as we break it down block by block.

The first block takes care of the x- and y-axes of our chart – here, we’ve created a number of vertical and horizontal lines using <line> elements in two separate groups, which have been evenly spaced out in our chart. These are then inserted onto the page using <use> elements – this would allow us to reuse these elements elsewhere on the page, although we’re only using them once in our demo.

Next up we added a <path> element – this looks after the block that represents our values on the page; we could have used a line, but turning it into a block gives it a little more interest. Over the top of this block, and at specified points, we then add miniature circles – these represent the data values we are using in our chart. To finish off our demo, we then added x- and y- labels using <text> elements; the last element is then rotated anti-clockwise to position it nearer the y-axis of our chart.

Okay – let’s change tack: we’ve covered the popular bar, line and pie charts; what’s left? Well, there is one: if you want something to help spark some dynamism to an online report, then it’s time to take a look at sparklines…and yes, pun most definitely intended!

Sparking Lines to Life

So far, our charts have all been larger stand-alone versions, designed to convey information visually from any web page. However, there may be instances where space might be at a premium – what do we do?

Well, how about using a mini chart? Officially created in 2006 (although some charts were seen as far back as 1988), sparklines are an effective way to display chart information inline within a text, particularly where space may be at a premium.

You might be forgiven for thinking that they require special techniques to construct; in reality, they can be built in the same way as standard SVG charts, albeit on a much reduced scale! To prove this, let’s crank up a little demo that shows off a mini line chart; we can use this as a basis for animating in a larger version at a later date.

CREATING SPARKLINE CHARTS

Okay – let’s make a start on our code:
  1. 1.

    We’ll begin by extracting a copy of the sparkline folder from the code download that accompanies this book – save it to our project area.

     
  2. 2.

    Next, go ahead and open sparkline.html in your usual text editor. Now copy the contents of inline.txt from the code download, in between the <p>...</p> tags, to create our SVG.

     
  3. 3.

    Save the file – if all is well, we should see a new mini chart appear, as indicated in Figure 8-6.

     
../images/461821_1_En_8_Chapter/461821_1_En_8_Fig6_HTML.jpg
Figure 8-6

Showing off our sparkline chart

See how easy that was? There really is nothing complicated about creating these mini charts – the best part though is that they can easily be made responsive, with little or no loss in quality.

If you would like to see additional examples of sparklines, code for two more examples is available in the download that accompanies this book. Go ahead and open additional code.html, then copy in the contents below the closing </p> tag of the first example. (The CSS is already stored in the demo for this extra code). Tip – I would recommend zooming in to see the effect close up!

The proof though is in the pudding – to see how they stack up against their larger cousins, let’s dive in and take a look at our code in more detail.

Breaking Apart Our Code

If you’re tasked with creating a sparkline chart (and let’s assume for the purpose of this book that it is a line chart), then we can use exactly the same principles as if you were creating one of its larger cousins.

The majority of the code for this example is just the container markup for our page, and some text; the real key to this demo is on line 14, where we have our <path> statement:
<path class="sp-line" d="M0 10.5c.403-.35 1.613-1.283....>

At first glance, it may not be easy to spot, but we’re actually using a series of Bezier curves, instead of straight lines. This gives a better effect for a sparkline – its normal size (i.e., really small), means that displaying numbers would be impossible, so we can go for the effect of a line graph instead.

But, the question I hear you all ask – how can I tell it’s a set of Bezier curves? Well, there are two ways to do it:
  • Use your browser to zoom in – notice how the ends of each line are not defined, but that we have a more curved effect?

  • Take a look at the <path> statement – if you look closely, there are only two commands in it; an M to move to absolute point 0, 10.5, and a little c to initiate a curve using a given set of points. We don’t use any other commands in the <path> element, which we would otherwise have if we were using normal lines.

The beauty though is that if we are using sparklines, then we can animate them to a larger size when hovering over them, using nothing more than standard CSS.

For an example of how you might animate a bar chart sparkline, head over to the pen created by the CSS Tricks website, at https://codepen.io/team/css-tricks/pen/1f82250d67c9f9d15b7339543c28cb20 . It’s a larger version, but the same principles still apply!

Okay – we’ve covered all of the common chart types; let’s move on and explore something completely different. Charts are a great way to convey information, but no matter how we skin them, they can still be somewhat static.

Thankfully there are ways to take our charts to the next level – making them interactive has almost become an essential part of designing any chart for display online! For example, we could just animate a segment from a pie chart – it might fly out a little, or scale up and show more information, as if viewed under a magnifying glass. Over the course of the next few pages, we’re going to explore a couple of simple techniques to get us started – there is so much more we can do, but we must begin somewhere!

Making Charts Interactive

A question, if I may - what do we mean by interactive?

Okay – at this point you’re probably asking yourselves what I mean by that question, but there is a good reason for asking it: think of it as a case of “How long is a piece of string?” Let me explain what I mean.

There are lots of ways to make a chart interactive; this might be as simple as hovering over a segment, providing a tooltip, or even making content appear in an overlay when clicking on a point on a chart. The key though is to treat it as if we’re adding animation: only add that which is necessary, and don’t go overboard.

To see what I mean, let’s put some of this into practice – our next demo will create a simple pie chart using a jQuery plug-in called drawPieChart. Available from https://github.com/githiro/drawPieChart , this simple chart is all that is needed to create an SVG-based pie chart. We’ll use this to create one based around popularity of browsers in April 2018 (using information from TechAdvisor.co.uk), with tooltips to show which is which – no prizes for guessing the most popular!

Before we get stuck into our code, let’s take a look at a screenshot of the chart we will create; the final version is shown in Figure 8-7.
../images/461821_1_En_8_Chapter/461821_1_En_8_Fig7_HTML.jpg
Figure 8-7

An interactive chart created with SVG

INTERACTING WITH A CHART

For this exercise, we need to avail ourselves of a copy of the interactive folder that comes in the code download that accompanies this book – you do not need to extract it, as we will copy the contents of each file as needed.

With this folder open and ready, let’s create that chart:
  1. 1.

    We’ll start by browsing to https://codepen.io , then click on Create.

     
  2. 2.

    We need to add in jQuery, which is a dependency for this charting library, so go ahead and click on Settings | Javascript | Quick-add (at the bottom), and select jQuery.

     
  3. 3.
    Next, go ahead and add the following HTML markup in the HTML pane:
    <h2>Beginning SVG: Creating an Interactive Chart</h2>
    <p>A chart to display the most popular browsers in use, as at April 2018:</p>
    <div id="pieChart" class="chart"></div>
     
  4. 4.

    We need to add a number of CSS styles, so for this, open the styles.txt file from the interactive folder in the code download that accompanies this book, and then copy the contents into the CSS pane.

     
  5. 5.

    Our chart won’t look up too much though, without the magic that makes it happen. For this we need to add our JavaScript – go ahead and copy the contents of script.txt from the same interactive folder into the JS pane.

     
  6. 6.

    With the code in place, go ahead and click on Save; you can save it as Anonymous if prompted, or use your own credentials if you already happen to have an account on Codepen.

     

With the chart now saved, we can preview the results of our work – we should see a chart appear as shown at the start of this exercise. It shows a tooltip where we’ve hovered over one of the segments, to see just how popular the browser is (figures given are in percentages).

There are a couple of points of note though for this demo – notice some of the color names we’ve used? These are specifically designed for use in SVG; you can see a full list of names at http://www.december.com/html/spec/colorsvg.html . I would also point out something we touched on back in Chapter 7, Optimizing SVG.”

The original demo hasn’t been updated for some time – it contains a number of floating point numbers (as shown in Figure 8-8), which makes for bloated code in SVG. If we were building from scratch, the number should be optimized with as few decimal places as possible!
../images/461821_1_En_8_Chapter/461821_1_En_8_Fig8_HTML.jpg
Figure 8-8

An extract of our code from Codepen

You can see a completed version of this chart at https://codepen.io/alexlibby/full/JvYpNb  – hit the Change View button and select Editor View to see the code.

Animating Chart Content

If someone asked me to move after a large dinner on a Sunday afternoon, then chances are the only place I would have in mind is the sofa, so I can relax and let the meal digest!

This aside, making things move – and in particular when referring to charts – has almost become an essential part of creating charts that are displayed online. Sure, static charts can and will display our information, but to really engage users, we need to add something that provides a little extra sparkle and encourages a visitor to interact with our content.

There are several ways we can do this: two that come to mind are to animate segments (such as in radial charts) or provide a tooltip that conveys additional information. We’ve already touched on how to add in the latter in the previous demo, using nothing more than a simple jQuery-based plug-in. This time, let’s switch focus, and start with adding animation using nothing more than pure CSS.

Animating Charts Using CSS

Cast your mind back to the donut demo we created earlier in this chapter – it’s a nice design, but somewhat static, wouldn’t you agree? Sure, it conveys the right information, but we’re not designing for print! To give it a little sparkle, we can use standard CSS animation to animate one of the elements within our chart. This is just one of many ways we could take our charts up a level; the same principles might also apply to line or bar charts too.

To see how easy it is, we’re going to animate the stroke-dashoffset effect on the donut example we built earlier in this chapter. It’s a simple effect, but it is a great way to illustrate the type of changes we can make to existing charts.

ANIMATING CONTENT

Let’s make a start on updating our code:
  1. 1.

    We’ll begin by extracting copy of the animatechart folder that comes in the code download that accompanies this book – save this to the root of our project folder.

     
  2. 2.

    Now go ahead and change the opening <svg> tag as indicated:

    <svg viewbox="-10 -3 53.83098862 53.83098862" width="300" height="300" >

     
  3. 3.
    We have to replace our SVG markup, so it fits in the viewBox – go ahead and replace lines 18–20 with this:
    <circle class="circle-back" cx="16.91549431" cy="16.91549431" r="15.91549431" />
          <circle class="circle-front" cx="36.91549431" cy="16.91549431" r="15.91549431" />
          <text x="17" y="36">25%</text>
     
  4. 4.

    Save animatechart.html, then go ahead and open a copy of animate.css, and remove the styles from the circle style rule, at line 18, to the end of the file.

     
  5. 5.
    Leave a blank line, then copy and paste the following code after the svg style rule:
    .circle-back { stroke: #efefef; stroke-width: 0.3rem; fill: none; }
    .circle-front { stroke: url(#gradient); stroke-width: 0.2rem;  stroke-dasharray: 25,100; stroke-linecap: round; animation: circle-chart-fill 2s reverse; transform: rotate(-90deg); transform-origin: center; fill: none; }
    text { font-family: inherit; font-size: 1.2rem; transform: scale(0.5); }
    @keyframes circle-chart-fill { to { stroke-dasharray: 0 100; } }
     
  6. 6.

    Save the file – if we preview the results, we should see the bar start to animate in a clockwise direction, as indicated in Figure 8-9.

     
../images/461821_1_En_8_Chapter/461821_1_En_8_Fig9_HTML.jpg
Figure 8-9

Animating a donut chart

Our animation demo should by now look very familiar – we’ve used the same styling as in the donut demo from earlier, but this time around adding our animation to make the dark ring start to slide round from position 0 to 25%. We could have easily added more though – what about animating the percentage figure, so it increases as the bar slides round, for example?

That said, there are a couple of important changes to our code that are of interest to us – they can be found in the .circle-front and @keyframes rules :
.circle-front {
  ...
  stroke-linecap: round;
  animation: circle-chart-fill 2s reverse;
  transform: rotate(-90deg);
  transform-origin: center;
}
…and the new circle-chart-fill keyframe animation:
@keyframes circle-chart-fill {
  to { stroke-dasharray: 0 100; }
}

Notice how we’ve not included a stroke-dashoffset value this time – changes to animate the stroke-dasharray from 0 to 25%, make the stroke-dashoffset value redundant. Indeed, if we were to add it in, you will see the animation start from further round, which destroys the aim of animating the first quarter of our circle! It would also make the transform and transform-origin rules redundant; these were added in to counteract the fact that stroke-dasharray starts from the 3 o’clock position, and not top dead center.

Notice the use of 0 100 in the stroke-dasharray keyframe? This is to ensure that the gap between each segment of stroke-dasharray is evenly spaced; the values used mean that the start point for each dash will be top dead center, which is why you only see one, not multiple dashes. Think of it as dashes drawn on paper – spacing is key!

Okay – let’s take things up a notch: we’ve created a simple animation using pure CSS, but there is more we can do when working with charts and SVG. We’ve already been introduced to some of the key techniques back in Chapter 6, “Animating Content” and will see more in the next chapter. As a taster though, let’s take a look at how we might use a library to animate charts – there’s no better alternative than revisiting Snap.svg, to see how it can take things up a level when working with SVG charts.

Animating Charts with Snap.svg

If you as a developer are ever tasked with animating content, then a natural step would be to consider using CSS; it has come up to such a level that it is beginning to snap at the heels of heavyweight animation! It still has some way to go, but current standards allow so much more than would have been capable 5 to 10 years ago.

This said, there are indeed still occasions where using JavaScript (or a third-party library) are a necessity; there are several options available to us, but the one considered most popular is Snap.svg. It’s easy to see why – the syntax is very similar to jQuery, which makes it easy to learn and use in our projects, if you already use it. For our next project, we’re going to create a simple demo of a bar chart – this time around, it’s time for it to become a little animated (if you pardon the terrible pun!).

ANIMATING USING SNAP

For our next exercise, we’ll focus on creating the Snap JavaScript to run our demo – the rest of the code is available in the snap folder within the code download that accompanies this book:
  1. 1.

    We’ll begin by extracting a copy of the animatesnap folder from the code download that accompanies this book – save it to our project folder.

     
  2. 2.
    Go ahead and open animatesnap.js – we need to add our JavaScript, which we will do block by block, starting with the initiator for our bar chart:
    var s = Snap("#barchart");
    var button1 = Snap("#button1");
    var button2 = Snap("#button2");
     
  3. 3.
    Next come the buttons and add text – add this after the initiating block, leaving a blank line first:
    //create buttons
    button1.rect(30, 0, 150, 30, 0).attr({ fill:"#fff" });
    button2.rect(30, 0, 150, 30, 0).attr({ fill:"#fff" });
    //add text to buttons
    var label_1 = button1.text(50, 20,"Show chart 1");
    var label_2 = button2.text(50, 20,"Show chart 2");
     
  4. 4.
    We can now add the code to create the bars, which will group into one element, and apply attributes:
    //create bars
    // rect(xCoords, yCoords, width, height, border-radius)
    var bar1 = s.rect(100, 10, 0, 5, 0).attr({fill: "darkgrey"});
    var bar2 = s.rect(100, 20, 0, 5, 0).attr({fill: "navajowhite"});
    var bar3 = s.rect(100, 30, 0, 5, 0).attr({ fill: "silver" });
    var bar4 = s.rect(100, 40, 0, 5, 0).attr({ fill: "black" });
    var bar5 = s.rect(100, 50, 0, 5, 0).attr({ fill: "slategrey" });
    //put the 5 bars into one group
    var bars = s.group(bar1, bar2, bar3, bar4, bar5);
    //apply attributes to all bars at once via the group
    bars.attr({
      stroke: "rgba(0,0,0,0.2)",
      strokeWidth: 0.2
    });
     
  5. 5.
    Last but by no means least, come the event handlers, which use the .animate() method to animate our graph:
    //add click event listeners
    button1.click(function () {
      bar1.animate({ height: 5, x: 20, y: 10, width: 60 }, 1100, mina.bounce);
      bar2.animate({ height: 5, x: 20, y: 20, width: 100 }, 1150, mina.bounce);
      bar3.animate({ height: 5, x: 20, y: 30, width: 220 }, 1200, mina.bounce);
      bar4.animate({ height: 5, x: 20, y: 40, width: 10 }, 1250, mina.bounce);
      bar5.animate({ height: 5, x: 20, y: 50, width: 40 }, 1300, mina.bounce);
    });
    button2.click(function () {
      bar1.animate({ height: 5, x: 20, y: 10, width: 150 }, 1100, mina.bounce);
      bar2.animate({ height: 5, x: 20, y: 20, width: 10 }, 1150, mina.bounce);
      bar3.animate({ height: 5, x: 20, y: 30, width: 20 }, 1200, mina.bounce);
      bar4.animate({ height: 5, x: 20, y: 40, width: 100 }, 1250, mina.bounce);
      bar5.animate({ height: 5, x: 20, y: 50, width: 70 }, 1300, mina.bounce);
    });
     
  6. 6.

    At this point, go ahead and save your work – if all is well, when previewing the results, we will see the chart shown in Figure 8-10, once “Show chart 2” has been clicked.

     
../images/461821_1_En_8_Chapter/461821_1_En_8_Fig10_HTML.jpg
Figure 8-10

Creating a chart with Snap.svg

We now have a working demo that uses Snap.svg – although the markup may look minimal, this is because the magic happens in the script. This is just a taster of how we can easily make use of Snap.svg to animate content, particularly when we have more complex requirements – there are a few key points in this code, so let’s pause for a moment to explore it in more detail.

Breaking Down Our Code

If we take a look at the code in more detail, we could easily be forgiven for thinking that it might not work – after all, it looks very much like standard jQuery, yet there is not a single reference to that library in sight!

This is one of the key benefits of using Snap.svg – it has been designed to make it easy to learn, particularly for those familiar with jQuery. We kick off our demo by initializing three objects – our SVG container, plus two buttons; the code uses a syntax similar to initializing objects in jQuery, albeit with Snap, instead of a $.

Next up, we create two buttons and apply text to both, using the button.text() property ; to this we assign appropriate values to determine their size and labels. We then create five bars using s.rect(), before grouping them together (to allow us to apply the same values to each, in one go). These form the basis for our chart. You will notice that the color scheme used here (and throughout this book) is based on various shades of black, gray, or white; this is purely for printing purposes. We can of course use any colors at this point; Hex codes, color names or RGB values work fine.

Last but by no means least, is where the real magic happens – we set up animate commands for each of the bars in turn, using the buttonX.click() event handler (where X is either 1 or 2). The syntax here is identical to basic jQuery – we first specify the properties to animate (here, it is height, x, y, and width), before specifying the duration in milliseconds and closing with an optional easing effect.

Okay – let’s move on: over the course of these pages, we’ve covered a lot of content around creating simple charts and providing some form of animation. Before we switch topics, I want to give you a little inspiration – as a starter for ten: have you ever created an infographic before?

Making Charts Interactive – a Postscript

When researching for this book, I spent time exploring infographic charts – for the uninitiated, these is a way of presenting information in a visually appealing manner, which is more than just a simple chart. In many cases, these infographics can be interactive; they can be somewhat large and complex to create though!

Infographics have been in use for many years – the original principles date back from 1857, although people have been known to use very early versions from as far back as the early 17th century. Today, it’s a tool that is suited for use on the web, and it is ideal for incorporating SVG graphics. Part of this is, of course, the ability to retain a sharp image, no matter what it’s size; it can be made responsive without too much additional markup.

To see what I mean, and the inspiration for this little postscript, take a look at “The Evolution of the Web,” hosted at http://www.evolutionoftheweb.com/ . It’s a really visual site that makes use of SVG. If you browse to it now, then use your browser’s DOM Inspector and search for the term “svg,” you will soon see proof (such as the example shown in Figure 8-11).
../images/461821_1_En_8_Chapter/461821_1_En_8_Fig11_HTML.png
Figure 8-11

The art of possible with SVG infographics...

Unfortunately, for reasons of space, we can’t explore the site in any great depth  – the code base is enormous! However, I would recommend taking a look at the compiled markup in a DOM inspector; the markup on its own isn’t enough, as most of the functionality is provided through using JavaScript (and jQuery). It does go to show that SVG really is versatile – you are only limited by your imagination!

Exploring Other Library Options

Up until now, several of the demos that we’ve created, and which contain animated elements, use the Snap.svg library. There is a reason for this – a check online will soon tell you that it is one of the most popular libraries for animating SVG elements!

However, this does not mean that we are limited in choice – far from it. There are dozens of libraries available online; we are spoilt for choice! There are a few questions we can ask to help select a library suitable for our needs, such as:
  • Is the library paid for, or a free one? If you have the budget available, then a paid-for option might be suitable, otherwise a free library will be your only option.

  • Is Open Source a possibility? This will depend on licensing compatibility – are you redistributing your solution, or will it remain internal?

  • Does your project have any dependencies? You may find you need something such as the SVG library, D3, or jQuery, or that there are no dependencies to consider.

  • What kind of features or support do you need? Does a library offer the feature set or support you need for your project? Is help available from the developer (or others), either on a community basis, or paid-for as an extra (or in the license)?

To help get you started, there are a few examples you can take a look at:
  • D3.js – available from https://d3js.org/ ; this is perfect for visualizing data-driven documents and is sometimes a dependency for other charting libraries such as C3 ( http://c3js.org/ ).

  • Chartist – weighing in at only 10KB and downloadable from https://gionkunz.github.io/chartist-js/ ; this is designed for simple chart construction, where the feature set doesn’t need to be extensive.

  • https://stanko.github.io/sektor/  – I’ve picked this out as an example of one of the smaller libraries that serves a single purpose: to create and animate SVG circle sectors. It is still fairly new, and only works with more modern browsers (sorry IE9 or below!).

  • AmCharts – Hosted at https://www.amcharts.com/ , this is a very detailed option that allows both online and offline creation of charts. There is a bit of a learning curve involved but worth spending time on to really understand how we can create visually appealing charts, before committing to an offline solution.

On that note – I’ve just talked about creating charts online; is there a good reason for doing so? Well, creating SVG charts can be a double-edged sword – we can make it as simple or as complex as we need!

Creating charts online is a good way to focus on how our chart looks, while the hosting site takes care of writing the code – in the case of our next demo, we can even export it for offline use, so that the same code can be used in both online and offline projects. Interested? Let’s take a look and see what this means for us in practice.

Creating Charts Online Using amcharts.js

Throughout the course of this chapter, we’ve created several different types of charts using SVG – the format lends itself particularly well to creating charts, as we can resize without loss of quality, and retain a high level of accessibility for those who need assistance.

There may be occasions when creating a chart from scratch is overkill, or if a project throws up uncertainty around how a chart might look. Instead of spending time creating something from scratch (as such), we can use an online service to mock up our chart relatively quickly. One such service is AMCharts, available at https://www.amcharts.com ; this has the added benefit of allowing us to export code for direct offline use, once we’ve completed our design.

To see what I mean, let’s take a brief look at using it – it’s a highly configurable tool, so it’s fair to say that the learning curve is somewhat heavy; it is definitely worth spending time getting familiar with it! With that in mind, we should make a start on our next exercise:

USING AMCHARTS

For the purposes of this exercise, I’ve created a sample chart using figures from http://gs.statcounter.com/browser-market-share  – you can view it at https://live.amcharts.com/Y4NzI/edit/ ; we’ll use this to have a play with the service.
  1. 1.

    First – go ahead and browse to the above link; we’ll see the chart shown in Figure 8-12.

     
../images/461821_1_En_8_Chapter/461821_1_En_8_Fig12_HTML.jpg
Figure 8-12

Our graph, made using AMCharts online

  1. 2.
    You will see a Code tab just below the chart; click on it.
    Try changing the value in the Font Size spinner box – you will see the chart automatically update with the new size. If you take a look at the HTML code, you will see the value you select against the fontSize property (shown here, increased to 17 from 11): "backgroundAlpha": 0.8,
        "fontSize": 17,
        "theme": "default",
     
  2. 3.
    On the right side of the screen, are a series of small buttons – these control the theme. Click on one to change the current theme; you will see the HTML code update automatically.
    "startDuration": 1,
    "backgroundAlpha": 0.8,
    "theme": "patterns",
    "categoryAxis": {
     
  3. 4.

    Scroll down the HTML code further, until you see a fillColors entry. This controls the fill color for one of the bar types; try changing the one under “Firefox” to “#8123FC”. It should turn a medium purple color in the chart.

     
  4. 5.

    Click on Legend in the left menu list – you will see a number of options show in a submenu. These correspond to the “legend” entry in the HTML, where we have entries such as “labelWidth.” Try changing Label width in the menu – notice any difference in the chart?

     
In this demo, we’ve only tweaked a couple of settings, but there is so much more available to us; it is definitely worth spending time with changing the settings, so you can see how tweaking one affects the exported code. There are a few pointers that might help speed up the process:
  • Don’t worry about how the code is created – AMCharts will allow you to export the code for reuse offline, so focus on what the chart looks like, not the code behind.

  • Consider installing and using a color picker plug-in for your browser – it makes it much easier to track which color is being used and where, so you can update the code.

  • Take a look at the demos – there are plenty of good examples, which come with code. You can easily copy over the configuration code for a setting, as long as you match where it needs to be inserted in your code.

  • Some of the settings don’t take effect unless you hit the Save button; if you make a mistake, simply refresh the page to reset it back to the last known working state.

At this point it’s over to you – AMCharts is infinitely configurable, so I would recommend spending time working your way through settings, to see how they influence your chart (and your code). AM Charts can also be used offline, so any settings you change online can be used as-is in your own projects.

If you would like to see AMCharts in action offline, try out this demo on Codepen: https://codepen.io/amcharts/pen/ogwNob

Summary

Creating charts affords us a great opportunity to create something visually appealing – after all, the saying “a picture is worth a thousand words” is especially apt when communicating data using charts! It’s no different if we add SVG into the mix – over the course of this chapter we’ve covered a number of useful techniques for this, so let’s review what we have learned

We kicked off with a quick foray into the benefits of using SVG, but particularly for charting – we then swiftly moved on to creating examples of some of the more common types of charts, such as bar, pie, or line. Next up came a look at how we can make our charts interactive – we created a simple example with tooltips, as a taster of what is possible. We then took a look at how we can animate chart elements – with the medium of online, we can do more than we might otherwise be able to in print, so clearly an opportunity not to be missed! We then rounded out the chapter with a quick look at an alternative to creating offline charts, which we can use to develop our solution before committing it to code.

Phew – it may not look much, but we’ve certainly covered a lot! Our journey continues on apace; we’ve already touched on using SVG libraries throughout the book, so why not spend a little more time to explore what we can achieve, in greater detail? There are several good libraries available online, so as someone once said, there’s no time like the present, to take a look…

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.28.9