您的位置:首页 > Web前端 > JavaScript

Flot tutorial: Javascript 脚本创建简单图形报表示例

2013-10-05 14:11 525 查看
source: http://2toria.com/2012/10/09/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>



Some other good stuff:

Linking
to external files in web development
A guide
to commenting code
jqBullet
– bullet graphs for wepages
Time to write
Custom lists
in Excel

Posted on October
9, 2012 by Matt.
This entry was posted in Charts, Web
Development and tagged charts, flot, javascript,jquery.
Bookmark the permalink.

« Mean
vs Median – What’s the Difference?
A
cautionary tale about software testing (and cheap kitchen drainer baskets) »


8 Comments



Gunther van den Bergh

January 20, 2013 - 6:50 pm | Permalink

Brilliant article – this is EXACTLY what I was looking for. Many thanx.



Matt

January 20, 2013 - 10:53 pm | Permalink

You’re welcome!



Timo

January 25, 2013 - 10:57 am | Permalink

You have just made my day, am even leaving the library coz its like am done with what i wanted to do



Rahul

April 21, 2013 - 6:27 pm | Permalink

Hi Matt,

That was really a helpful tutorial for me as i am a beginner for using FLOT and i am a bug fan of jQuery but i dont know much about it..:) but i still try to use it.

Can you please add some more tutorial from your side for FLOT like legends , diffferent types of views and mainly how to connect FLOT with SQL Server for capturing data available / updated in Server.

Thank You,

Rahul Parab





MOCR

May 13, 2013 - 5:04 pm | Permalink

Hi,

Thanx,

How do change the color of each bar?





Matt

May 13, 2013 - 7:21 pm | Permalink

Hi Rahul

Thanks for your reply. I’m planning on working on a few more flot tutorials as I’ve had a number of requests for more. Keep an eye out!

Mat



Matt

May 13, 2013 - 7:21 pm | Permalink

MOCR,

I’m just looking into it now. Hopefully will post another tutorial soon on how to do this.

Mat

Pingback: Time
to write »
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: