highcharts document

来源:互联网 发布:python 最大回撤 编辑:程序博客网 时间:2024/05/29 08:46





How To Use

Table of contents

  1. Installation
  2. How to set up the options
  3. Preprocessing the options
  4. Live charts
  5. Exporting module
  6. Freeform drawing

1. Installation

  1. Highcharts uses either jQuery, MooTools or Prototype for some common JavaScript tasks. You need to include the JavaScript files in the section of your web page *). If you already have jQuery included, you can skip the first one. Use this code to include Highcharts with jQuery:
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js" type="text/javascript"></script><script src="/js/highcharts.js" type="text/javascript"></script>
    While the jQuery adapter is built into Highcharts and Highstock, the MooTools adapter has to be included separately. Use this code to include Highcharts with MooTools:
    <script src="https://ajax.googleapis.com/ajax/libs/mootools/1.3.0/mootools-yui-compressed.js" type="text/javascript"></script><script src="/js/adapters/mootools-adapter.js" type="text/javascript"></script><script src="/js/highcharts.js" type="text/javascript"></script>
    If you're installing Highstock, the procedure is the same as above, except the JavaScript file name is highstock.js rather than highcharts.js. *) Highcharts version 1.x relied on excanvas.js for rendering in IE. From Highcharts 2.0 (and all Highstock versions) IE VML rendering is build into the library.
  2. In a script tag in the head of your web page, or in a separate .js file, add the JavaScript code to initialize the chart. Note that the id of the div where you want to put the chart (see #3) is given in the renderTo option below:
    var chart1; // globally available$(document).ready(function() {      chart1 = new Highcharts.Chart({         chart: {            renderTo: 'container',            type: 'bar'         },         title: {            text: 'Fruit Consumption'         },         xAxis: {            categories: ['Apples', 'Bananas', 'Oranges']         },         yAxis: {            title: {               text: 'Fruit eaten'            }         },         series: [{            name: 'Jane',            data: [1, 0, 4]         }, {            name: 'John',            data: [5, 7, 3]         }]      });   });
    The code above uses the jQuery specific way of launching code on document ready, as explained at the jQuery website. If you use MooTools, instead of the $(document).ready() syntax you do it slightly differently:
    <script type="text/javascript">   window.addEvent('domready', function() {      var chart1 = .......
    If you're inserting a Stock chart, there is a separate constructor method called Highcharts.StockChart. In these chart, typically the data is supplied in a separate JavaScript array, either taken from a separate JavaScript file or by an Ajax call to the server.
    var chart1; // globally available$(document).ready(function() {      chart1 = new Highcharts.StockChart({         chart: {            renderTo: 'container'         },         rangeSelector: {            selected: 1         },         series: [{            name: 'USD to EUR',            data: usdtoeur // predefined JavaScript array         }]      });   });
  3. Add a div in your webpage. Give it an id refering to the renderTo option in #2, and set a specific width and height which will be the width and height of your chart.
    <div id="container" style="width: 100%; height: 400px"></div>
  4. Optionally, you can apply a global theme to your charts. A theme is just a set of options that are applies globally through the Highcharts.setOptions method. The download package comes with four predefined themes. To apply a theme from one of these files, add this directly after the highcharts.js file inclusion:
    <script type="text/javascript" src="/js/themes/gray.js"></script>

2. How to set up the options

Highcharts uses a JavaScript object structure to define the options. The options are nested into categories. The options are mainly strings and numbers, but some are arrays, other objects or even functions. When you initialize the chart using new Highcharts.Chart, the options object is the first parameter you pass.

If you want to apply a set of options to all charts on the same page, use Highcharts.setOptions like shown below.

See #3 above for an example of an options object. For more examples see the Highcharts demo gallery or the Highstock demo gallery. For a full reference of the options available, see the Highcharts options reference and the Highstock options reference.

3. Preprocessing the options

To get the most out of Highcharts, it is important to understand how the configuration object works and how it can be altered programmatically. These are some key concepts on JavaScript objects:

  • The Highcharts options in the examples are defined as object literals. By notating the configuration this way, we can have a clean, human readable and low space consuming config object. This complicated code is perhaps more familiar to developers with a background from C-type languages:
    // Bad code:var options = new Object();options.chart = new Object();options.chart.renderTo = 'container';options.chart.type = 'bar';options.series = new Array();options.series[0] = new Object();options.series[0].name = 'Jane';options.series[0].data = new Array(1, 0, 4);
    As JavaScript object literals, we would write it like below. Note that the two options objects will produce exactly the same result.
    // Good code:var options = {    chart: {        renderTo: 'container',        defaultSeriesType: 'bar'    },    series: [{        name: 'Jane',        data: [1, 0, 4]    }]};
  • After an object is created using the object literal notation, we can extend its members by the dot notation. Say we have an object like defined in the "Good code" above. The code below adds another series to it. Remember options.series is an array, so it has a push method.
    options.series.push({    name: 'John',    data: [3, 4, 2]})
  • Another fact that can come in handy when working on JavaScript objects, is that the dot notation and square bracket notation are equivalent, so you can access all members by their string names. Which in practice means that
    options.renderTo
    is always the same as
    options['renderTo']

3.1 Case study: preprocessing the data

This example shows how to set up the basic chart options first, then do an Ajax call for the data, parse the data and add them in the proper format to the options. In this example, jQuery is used for handling Ajax, but you could just as well use MooTools' or Prototype's similar functions. All of the code runs in the$(document).ready event handler. The example can be seen live at data-from-csv.htm.

  1. Create an external CSV file containing only the data. In this example, the file looks like below. The first line lists the categories with a dummy name in the first position. The subsequent lines list the data series name in the first position and values in the subsequent positions. In real life, you will often create the contents of this file using PHP or other server side programming languages. Or you may choose to use other markup formats like XML or JSON. In those cases, jQuery can also parse the data for you natively.
    Categories,Apples,Pears,Oranges,BananasJohn,8,4,6,5Jane,3,4,2,3Joe,86,76,79,77Janet,3,16,13,15
  2. Define the initial, basic options. Note that we create empty arrays for the categories and series objects, so that we can just push values to them later.
    var options = {    chart: {        renderTo: 'container',        defaultSeriesType: 'column'    },    title: {        text: 'Fruit Consumption'    },    xAxis: {        categories: []    },    yAxis: {        title: {            text: 'Units'        }    },    series: []};
  3. Put it all together. We use the jQuery.get method to get the contents of the data.csv file. In the success callback function, we parse the returned string, add the results to the categories and series members of the options object, and create the chart. Note that we can't create the chart outside the Ajax callback, as we have to wait for the data to be returned from the server.
    $.get('data.csv', function(data) {    // Split the lines    var lines = data.split('\n');        // Iterate over the lines and add categories or series    $.each(lines, function(lineNo, line) {        var items = line.split(',');                // header line containes categories        if (lineNo == 0) {            $.each(items, function(itemNo, item) {                if (itemNo > 0) options.xAxis.categories.push(item);            });        }                // the rest of the lines contain data with their name in the first position        else {            var series = {                data: []            };            $.each(items, function(itemNo, item) {                if (itemNo == 0) {                    series.name = item;                } else {                    series.data.push(parseFloat(item));                }            });                        options.series.push(series);            }            });        // Create the chart    var chart = new Highcharts.Chart(options);});

4. Live charts

After a chart has been defined by the configuration object, optionally preprocessed and finally initialized and rendered using new Highcharts.Chart(), we have the opportunity to alter the chart using a toolbox of API methods. The chart, axis, series and point objects have a range of methods like updateremove,addSeriesaddPoints and so on. The complete list can be seen in the API Reference under "Methods and Properties" at the left.

4.1 Case study: a live connection to the server

The following example shows how to run a live chart with data retrieved from the searver each second, or more precisely, one second after the server's last reply. It is done by setting up a custom function, requestData, that initially is called from the chart's load event, and subsequently from its own Ajax success callback function. You can see the results live at live-server.htm.

  1. Set up the server. In this case, we have a simple PHP script returning a JavaScript array with the JavaScript time and a random y value. This is the contents of the live-server-data.php file:
    <?php// Set the JSON headerheader("Content-type: text/json");// The x value is the current JavaScript time, which is the Unix time multiplied by 1000.$x = time() * 1000;// The y value is a random number$y = rand(0, 100);// Create a PHP array and echo it as JSON$ret = array($x, $y);echo json_encode($ret);?>
  2. Define the chart variable globally, as we want to access it both from the document ready function and our requestData funcion. If the chart variable is defined inside the document ready callback function, it will not be available in the global scope later.
    var chart; // global
  3. Set up the requestData function. In this case it uses jQuery's $.ajax method to handle the Ajax stuff, but it could just as well use any other Ajax framework. When the data is successfully received from the server, the string is eval'd and added to the chart's first series using the Highcharts addPoint method. If the series length is greater than 20, we shift off the first point so that the series will move to the left rather than just cram the points tighter.
    /** * Request data from the server, add it to the graph and set a timeout to request again */function requestData() {    $.ajax({        url: 'live-server-data.php',        success: function(point) {            var series = chart.series[0],                shift = series.data.length > 20; // shift if the series is longer than 20            // add the point            chart.series[0].addPoint(point, true, shift);                        // call it again after one second            setTimeout(requestData, 1000);            },        cache: false    });}
  4. Create the chart. Notice how our requestData function is initially called from the chart's load event. The initial data is an empty array.
    $(document).ready(function() {    chart = new Highcharts.Chart({        chart: {            renderTo: 'container',            defaultSeriesType: 'spline',            events: {                load: requestData            }        },        title: {            text: 'Live random data'        },        xAxis: {            type: 'datetime',            tickPixelInterval: 150,            maxZoom: 20 * 1000        },        yAxis: {            minPadding: 0.2,            maxPadding: 0.2,            title: {                text: 'Value',                margin: 80            }        },        series: [{            name: 'Random data',            data: []        }]    });        });

5. Exporting module

From version 2.0 an exporting module is available for Highcharts, which allows users to download images or PDF's of your charts. This module consists of an extra JavaScript file, exporting.js, and a web service or server module written in PHP. Highslide Software offers the exporting web service free of charge. If you include the exporting module in your charts, two buttons will appear in the upper right. One button prints the chart, which is done on the client side only. The other button handles exporting. By default, an SVG representation of the chart is sent by POST to http://export.highcharts.com, where it is converted using Apache's Batik converter to PDF, PNG or JPEG.

See the navigation and exporting reference items for a full documentation for the options available. Also see under "Methods and Properties" in the reference for members releated to exporting.

5.1 Client side setup

Add the exporting module JavaScript file after your highcharts.js file.

<script  src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"  type="text/javascript"></script><script src="/js/highcharts.js" type="text/javascript"></script><script src="/js/modules/exporting.js" type="text/javascript"></script>

5.2 Server module setup

If you want to set up this web service on your own server, the index.php file that handles the POST is supplied in the download package inside the/exporting-server directory.

  1. Make sure that PHP and Java is installed on your server.
  2. Upload the index.php file from the /exporting-server directory in the download package to your server.
  3. In your FTP program, create directory called temp in the same directory as index.php and chmod this new directory to 777 (Linux/Unix servers only).
  4. Download Batik from http://xmlgraphics.apache.org/batik/#download. Find the binary distribution for your version of jre
  5. Upload batik-rasterizer.jar and the entire lib directory to a location on your web server.
  6. In the options in the top of the index.php file, set the path to batik-rasterier.jar.
  7. In your chart options, set the exporting.url option to match your PHP file location.

As an ASP.NET alternative to our Java/PHP based server module, Clément Agarini has kindly shared his export module for ASP.NET.

6.0 Freeform drawing

Internally, Highcharts is equipped with a rendering module that acts as a wrapper for JavaScript access to SVG in modern browsers and VML in IE < 9. It has much in common with drawing tools like Raphaël or SVG jQuery. This drawing module can be used either to draw shapes or text on the chart, or even as a standalone drawing tool for HTML pages.

Inside a chart, the chart's renderer object is available as chart.renderer. To instanciate a new SVG drawing outside Highcharts, you call new Highcharts.Renderer(parentNode, width, height), where parentNode is the div or container element where you want the drawing to be placed.

The drawing API is documented in detail at /ref#renderer and /ref#element.

7. API reference

Proceed to the API Reference.

原创粉丝点击