官术网_书友最值得收藏!

Creating a line chart

Line charts are the most basic type of charts. They display a series of data points connected together by lines. Line charts are often used to visualize time series data.

There are various libraries that implement this charting functionality, both paid and free. We're going to use the Flot chart library. It's free, simple, and easy to use and it has been in active development for the past 4 years. It also aims to produce aesthetically pleasing charts.

In this recipe, we're going to make a time series chart that displays the outside temperature history for the past 24 hours.

Getting ready

We'll need to download Flot from the official website at http://www.flotcharts.org/, and extract the contents to a separate folder named flot.

How to do it...

Let's write the HTML and JavaScript code.

  1. Create a basic HTML page with a placeholder for our chart. We're also going to include jQuery (needed by Flot) and Flot itself. Flot needs to draw the chart canvas a placeholder div, so we're going to provide one. The chart placeholder needs to have its width and height specified, otherwise Flot will be unable to draw correctly:
    <!DOCTYPE HTML>
    <html>
        <head>
            <title>Chart example</title>
        </head>
        <body>
            <div id="chart" style="height:200px; width:800px;"></div>
            <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
            <script src="flot/jquery.flot.js"></script>
            <script type="text/javascript" src="example.js"></script>
        </body>
    </html>
  2. Add the code that draws our chart in example.js. The getData function generates some convincing-looking random data—you can easily replace it with a function that fetches data from the server. The data needs to be returned as an array of two-element arrays. The first (x axis) value in the pair is a standard UNIX timestamp in milliseconds as commonly used in JavaScript, while the second (y axis) value is the temperature.
  3. Drawing the chart is very simple. The $.plot function draws the chart in the specified placeholder containing the specified series with the specified chart options:
    $(function() {    
        function getData(cb) {
            var now  = Date.now();
            var hour = 60 * 60 * 1000;
            var temperatures = [];
            for (var k = 24; k > 0; --k)
                temperatures.push([now - k*hour,
                    Math.random()*2 + 10*Math.pow((k-12)/12,2)]);
            cb({data:temperatures});
        }
        getData(function(data) {
            $.plot("#chart", [data], {xaxis: {mode: 'time'}});
        });
    });

That's it! The following is how the end result looks like:

How it works...

The $.plot function takes three arguments:

  • The placeholder selector. This is where Flot will draw the chart.
  • The array of series to draw. Flot can simultaneously draw multiple series on the same chart. Every series is an object that must at least contain the data property. This property is an array of two-element arrays that are the x and y values of the series. Additional properties allow us to control the way the particular series is drawn—those will be explored in more detail in the next recipes. By default, Flot draws a regular line chart with a preset color.
  • An options object that contains extensive chart drawing options for the chart labels, axes, legend, and grid. These options will also be explored in the next recipes.

In this recipe we've specified the "time" mode for the x axis. This causes Flot to appropriately label the hours, days, months, or years on our axis (depending on the timespan of the data).

There's more...

The following is a simple Ajax replacement of the getData function, sending an Ajax request to a request handler hosted on the same domain at the path /chart to retrieve the chart data:

function getData(cb) {
    $.get('/chart').success(cb);
}
主站蜘蛛池模板: 交口县| 旌德县| 元谋县| 山东| 澄江县| 玛纳斯县| 凌海市| 靖州| 汝州市| 嘉义县| 增城市| 通河县| 财经| 桃江县| 吉木乃县| 兰西县| 九龙坡区| 交城县| 溧水县| 北辰区| 滨州市| 琼结县| 凤山市| 河间市| 兰坪| 方城县| 历史| 西青区| 星座| 吉木萨尔县| 乌拉特前旗| 武宣县| 九寨沟县| 大石桥市| 饶阳县| 临漳县| 两当县| 花莲市| 通海县| 库尔勒市| 措美县|