Tag Archives: charts

Charts Web Development

Flot tutorial: Creating a simple bar chart

I thought I’d take a slightly different direction re charting and data visualisation today and offer up a quick and easy tutorial on creating charts for the web using a jQuery plugin called ‘Flot’ (for those not in the know, jQuery is a javascript library developed to make web-based programming easier and quicker. There’s too much of it to talk about now, but if you’re interested follow this link).

So what is flot?

Flot is a charting library designed to make creating charts for the web an easier task. Without such a library there’s a pretty big learning curve and work just to get a few lines drawn on a webpage. Flot takes all that fuss and hassle away and just allows us to get on with creating stuff. OK, there’s still coding that needs to be done, but it’s simplified greatly.  Another great thing about flot is that is open-source and, as such, updated reasonably regularly.  There was a time when there were hardly any updates, but there now seems to be some movement.

In this article I’m just going to take you through a very basic tutorial on creating a simple bar chart using this brilliant tool.

What do I need?

Nothing really, just a computer with a text editor and a browser.

Setting up

First of all, create a folder called ‘Flot Learning’.

The next thing you need to do for this tutorial is place three javascript libraries in your folder. You can download the latest version of Flot here as a zip file.  Unzip the file and copy these three files to your folder:-

excanvas.min.js
jquery.flot.js
jquery.js

These are the javascript files that will do the heavy lifting for you. The excanvas file is needed if you want your charts to display in IE6/7. Without it, nothing will display in these earlier browsers. You’ll notice there are a lot of other js files in the download, but we won’t need these for this example.

OK, now create a new file in notepad (or your web development IDE, if you have one) and call it flot-simple.html (or whatever name you like).

With the file now open, copy and paste the HTML below. This will act as your template for the code to follow:-

<!DOCTYPE html>

<head>
<title></title>

<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="excanvas.min.js"></script>
<script type="text/javascript" src="jquery.flot.js"></script>

<style>
body {
     font-family: Arial;
}

#mycanvas {
     width: 500px;
     height: 300px;
}

</style>
</head>

<body>

<div id="mycanvas">

</div>

<script>

</script>

</body>
</html>

Let me quickly talk you through what this template is doing. In the three <script> lines we are linking to the three files you downloaded earlier. Following this we have some style instructions for the div. Normally you would put your style instructions in a separate file, but for simplicity’s sake I thought I’d add some page-level styling.

Finally we’ve created a div called “mycanvas”, which is the placeholder for our beautiful bar chart later on. The code to create the chart will be entered within the script tags near the bottom.

Make sense so far? If not you might need to read up a little bit more on basic HTML stuff to fully understand the meaning of the code in your file.

OK, then. Save your file and open it up in your browser and you should see absolutely nothing! If that’s the case we’re ready to move on.

Building the chart

In the bottom script tag, type the following:-

$(function() {

});

This is the wrapper for your charting code.

The first thing we need for our chart is some data. Let’s create a chart looking at seasonal sales figures for 2011:-

Spring:  2010
Summer:  2543
Autumn:  2520
Winter:  2354

Let’s start by putting the values into an array for use later. Type these bits inside the function we’ve just created:-

var myData = [[1,2010], [2, 2543], [3, 2520], [4, 2354]]

You’ll notice that the data is entered within a pair of square brackets, and each individual data point is entered within separate comma-separated square brackets, each of which contains two values. The first is the index of the data point you are plotting, and increments by one in this case, and the second is the value you want to plot on the chart.

OK..now the magic happens. Add the following:-

$.plot($("#mycanvas"), [
     {
          data: myData
     }
]);

The <script> section of your html file should now look like this:-

<script>
$(function() {
     var myData = [[1, 2010], [2, 2543], [3, 2520], [4, 2354]];

     $.plot($("#mycanvas"), [
          {
               data: myData
          }
     ]);

});
</script>

Save your file again and refresh the page in your browser. If everything is as it should be you should have something that looks like this:-

Do you? Excellent – we’re well on our way. OK, so you’ve created the most basic of charts using flot. No labels, no formatting, nothing. The default is a very simple line chart, as shown. Now we need to do something about how it looks. Let’s start by turning it into a bar chart, shall we? It is worth noting at this point that the chart is displayed just like any other page element, so you can move it around and display with any other content you choose. for this tutorial however we’re just going to stick with a chart on the page.

After the ‘data: myData’ part, add a comma, and on the next line type this: –

bars: { show: true }

(Please note, anything in curly brackets usually indicates something where multiple comma separated values can be added.

Refresh your browser and you should now see this:-

Happier? It’s great, isn’t it? I don’t like the colour much though, so let’s have a stab at it. Add another comma, and on the next line add:-

color: "#454d7d"

Save and refresh your browser again:-

So far so good? The color property must be in quotes and can be either a html color (ie ‘Gray’, ‘Red’ etc) or a color using hexadecimal notation as we just did.

Right then. What else is missing? I’m personally not too keen on being able to see the grid through the bars, so I’m going to change the opacity of the fill in the bars. We do this by adding another item between the curly brackets in the ‘bars’ section, so it looks like this:-

bars: {show: true, fill: 1}

The ‘fill’ property takes a value from 0 to 1 and acts as the opacity of the fill colour of the bar. The closer to 1 the less the opacity (or see-through-ability). Save and refresh again!

Better, but now it looks a bit too blocky. I’d like the bars to have a border…

In theory the bars already do have a border, it’s just that they are the same colour as the fill inside the bars, so what we need to do is change one of them. In Flot there is a fillColor property, which is entered under ‘bars’, so let’s for now just add that and add a lighter shade of blue. Your code for the bars should now look like this:-

bars: { show: true, fill: 1, fillColor: "#757dad" }

Note again that the fillColor property is entered within quotation marks as hexadecimal notation.

For reference (and just in case you’re getting lost at all), the code in the script tags should now look like this:-

<script>
$(function() {
     var myData = [[1, 2010], [2, 2543], [3, 2520], [4, 2354]];

     $.plot($("#mycanvas"), [
           {
                data: myData,
                bars: { show: true, fill: 1, fillColor: "#757dad" },
                color: "#454d7d"
           }
     ]);

});
</script>

Save and refresh!! All good so far:-

Right then. What’s missing now? We could do with better labelling of the x-axis, couldn’t we? Let’s get started!

There are a few ways we could go about doing this, but I’m going to opt for one which makes editing your chart much easier. We’re going to create an Options variable and store our display options in that. Add the following to your code, before the $.plot part of your code:-

var Options = {

}

The options for how the chart will display will appear as comma separated values between the curly brackets. Let’s start by changing the x-axis. We need to add labels, so let’s do that. Add the following between the curly brackets:-

xaxis: {ticks: [[1,"Spring"], [2, "Summer"], [3, "Autumn"], [4, "Winter"]] }

And click save. All we’ve done here is the same as we did when we added our data. We’ve four sets of comma separated values for each of the areas we’re reporting on. Make sure the first figure in each set (ie the number) matches the same number in the data).

If you were to refresh your browser at this point you wouldn’t see much, because we’ve done nothing with the new information. What we need to do is to add it to our Flot code.

Flot options are added to the $.plot part right after the last square bracket. In our case we’re just going to type the name of the variable (Options). Your code should look like this when you’ve done:-

<script>
$(function() {
     var myData = [[1, 2010], [2, 2543], [3, 2520], [4, 2354]];

    var Options = { xaxis: {ticks: [[1,"Spring"], [2, "Summer"], [3, "Autumn"], [4, "Winter"]] } }

     $.plot($("#mycanvas"), [
           {
                data: myData,
                bars: { show: true, fill: 1, fillColor: "#757dad" },
                color: "#454d7d"
           }
     ],Options);

});
</script>

I’ve highlighted the new code we’ve just discussed in blue to make it easier to see where it fits.

And…save and refresh one more time! You should see this:-

Not too bad…not too bad at all!! However, the finicky part of me isn’t happy that the x-axis labels don’t appear under the bars. Can we fix it? Yes, we can! Go back to the actual plotting code and add the following to the end after another comma:-

align: "center"

Which should leave your plot code looking like this:-

     $.plot($("#mycanvas"), [
           {
                data: myData,
                bars: { show: true, fill: 1, fillColor: "#757dad", align: "center" },
                color: "#454d7d"
           }
     ],Options);

Let’s save and refresh one last time for now. Here’s what’s left:-

Wonderful! Much, much better, don’t you agree?

And that’s it for now, I think. There’s so much more to Flot in terms of formatting, but I’m going to leave it here as I think you’ve learned a lot already. I’ll come back with a second part to this soon to discuss more formatting options, including grid lines and legends. If, in the meantime you want to learn more, Flot has some really good in-depth documentation here. It might be a little confusing if you’re not a javascript programmer, but if you use it based on the boilerplate code we’re left with it shouldn’t be too difficult to experiment with to make some great charts.

Flot doesn’t just do bar charts, either.  Check out the examples on the Flot website for some of the really cool stuff you can do with it.

Give the code a whirl and play around with some of the settings – if you’ve any questions or comments on this tutorial please do leave them after the post. I hope this has been of use to you and will be back soon with more Flot goodness!!

Finally, here’s the entire code we’ve just created:-

<!DOCTYPE html>

<head>
<title></title>

<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="excanvas.min.js"></script>
<script type="text/javascript" src="jquery.flot.js"></script>

<style>
body {
     font-family: Arial;
}

#mycanvas {
     width: 500px;
     height: 300px;
}

</style>
</head>

<body>

<div id="mycanvas">

</div>

<script>
     $(function() {
          var myData = [[1, 2010], [2, 2543], [3, 2520], [4, 2354]];

          var Options = { xaxis: {ticks: [[1,"Spring"], [2, "Summer"], [3, "Autumn"], [4, "Winter"]] } }

          $.plot($("#mycanvas"), [
               {
                   data: myData,
                   bars: { show: true, fill: 1, fillColor: "#757dad", align:"center" },
                   color: "#454d7d"
               }
         ],Options);

});
</script>

</body>
</html>
2toria

It’s been a while, but…

…actually, I have no excuse other than the fact that I’ve been really busy over the past few months, both at home and in the day job.  I’ve also been doing quite a lot of learning about web design and web application development so I can put into place a few ideas I’ve had rolling around in my head for some time.  More on those soon.  In the meantime, you can check out my new blog (if you’re interested in that sort of thing) over on webdev.2toria.com for some posts about the stuff I’ve been learning.

Anyway, dear readers, I just wanted to let you know I’ve not forgotten about you.  I’ve decided to become a little more active in this area again, so you can expect more Excel, data and visualisation stuff soon.  I also want to start tackling more awful wikipedia charts again in my continued mission for clearer data presentation.

Having said that, why don’t you have a go at it?  If you follow this link you’ll see a whole raft of pie charts that could do with some work.  All you need is a wikipedia account and some common sense and you too could make a big difference.

Try this one for starters (click the image to get to the wikimedia commons entry).  There’s a list of pages using the image further down the page (there’s a lot – surely somebody out there can do something better than this!!).

 


If somebody changes it in the next 48 hours I’ll do a post about it – now that’s encouragement for you!  Just let me know it was you in the comments..

Anyway.  More from me very soon – it’s been way too long.

Charts

Wikipedia – Changing Charts #2

The second in my Wikipedia chart-editing ‘project’ was this, which appeared in the article ‘Ageing of Europe‘, and displays population growth for Russia:-

Whilst it’s not the worst chart in the world, there were a few things I noticed that I was unhappy with.  First of all, the 3d effect.  That had to go.  Also, the nature of the information lends itself much better to a pair of lines for easier reading and interpretation, but there’s a minor problem – the dates are a little disjointed and move in five year increments until 2005, and then we’re seeing the data yearly.  I looked at the source of the data to see if I could find out anything else.  Here are the statistics the data is based on, according to the original chart (source):-

Years

Births

Deaths

Natural
increase, decrease (-)

Infant deaths
under 1 year old

1992

1587.6

1807.4

-219.8

29.2

1995

1363.8

2203.8

-840.0

24.8

2000

1266.8

2225.3

-958.5

19.3

2005

1457.4

2303.9

-846.5

16.1

2006

1479.6

2166.7

-687.1

15.1

2007

1610.1

2080.4

-470.3

14.9

2008

1713.9

2075.9

-362.0

14.4

2009

1761.7

2010.5

-248.8

14.3

2010

1789.6

2031.0

-241.4

13.4

As you can see, the data actually seems to have either been updated, or was incorrect in the first place, as it actually starts at 1992 and finishes at 2010.  There’s still not information for the missing years, however.

I decided to use this seemingly updated information for my chart remake.

And, here it is:-

Once again, I think this paints a clearer picture.  I normalised the date ranges so that each tick is a year – the markers in each line show points where we actually have data, which doesn’t show what happened between, say, 1992 and 1995, but flows and reads much better than before, I think.

Any thoughts/suggestions on this fix?

Charts

Wikipedia – changing charts #1

Some time ago, Jorge Camoes posted about bad charts in Wikipedia and rallied for changes to be made to some truly horrific examples of bad charting.  Last night whilst browsing I noticed a few examples myself and decided to make a start, as some of the examples provided by Jorge still hadn’t been changed.

The entry on Throughput Accounting contained this beauty:-

3d bars and general junk make this a typical bad chart.  I spent an hour or so trying to fix it up a bit.  I’m no expert on accounting, so I just rearranged things a little and tried to make things look clearer and simpler.  No 3d, clearer labelling and re-ordering of the axes resulted in this:-

It’s still not perfect,  but so much better than the original, or at least I think so.  It’s a start, anyway.  Your comments are more than welcome.

Additionally, I wholeheartedly recommend that you also seek out more examples of bad charting and do something to fix them up to make charts on Wikipedia more consistent and junk-free.