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:
2.
3.
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:
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.
4. 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:
5. var chart1; // globally available
6. $(document).ready(function() {
7. chart1 = new Highcharts.Chart({
8. chart: {
9. renderTo: 'container',
10. type: 'bar'
11. },
12. title: {
13. text: 'Fruit Consumption'
14. },
15. xAxis: {
16. categories: ['Apples', 'Bananas', 'Oranges']
17. },
18. yAxis: {
19. title: {
20. text: 'Fruit eaten'
21. }
22. },
23. series: [{
24. name: 'Jane',
25. data: [1, 0, 4]
26. }, {
27. name: 'John',
28. data: [5, 7, 3]
29. }]
30. });
});
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:
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 from CSV
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.
2. Categories,Apples,Pears,Oranges,Bananas
3. John,8,4,6,5
4. Jane,3,4,2,3
5. Joe,86,76,79,77
6. Janet,3,16,13,15
7. 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.
8. var options = {
9. chart: {
10. renderTo: 'container',
11. defaultSeriesType: 'column'
12. },
13. title: {
14. text: 'Fruit Consumption'
15. },
16. xAxis: {
17. categories: []
18. },
19. yAxis: {
20. title: {
21. text: 'Units'
22. }
23. },
24. series: []
};
25. 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.
26. $.get('data.csv', function(data) {
27. // Split the lines
28. var lines = data.split('\\n');
29.
30. // Iterate over the lines and add categories or series
31. $.each(lines, function(lineNo, line) {
32. var items = line.split(',');
33.
34. // header line containes categories
35. if (lineNo == 0) {
36. $.each(items, function(itemNo, item) {
37. if (itemNo > 0) options.xAxis.categories.push(item);
38. });
39. }
40.
41. // the rest of the lines contain data with their name in the first position
42. else {
43. var series = {
44. data: []
45. };
46. $.each(items, function(itemNo, item) {
47. if (itemNo == 0) {
48. series.name = item;
49. } else {
50. series.data.push(parseFloat(item));
51. }
52. });
53.
54. options.series.push(series);
55.
56. }
57.
58. });
59.
60. // Create the chart
61. var chart = new Highcharts.Chart(options);
});
3.2 Loading from XML
Loading data from an XML file is similar to the CSV approach. Highcharts does not come with a predefined XML data syntax, it is entirely up to you to write the XML and to define a parsing function for it. The downside of using XML over CSV is that it adds some markup to the data, leaving a larger footprint. How large the extra footprint is depends on how you mark up your data. For example, if you wrap each
point with a 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 update, remove, addSeries, addPointsand 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 server 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 loadevent, 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: 2. 3. // Set the JSON header 4. header(\"Content-type: text/json\"); 5. 6. // The x value is the current JavaScript time, which is the Unix time multiplied by 1000. 7. $x = time() * 1000; 8. // The y value is a random number 9. $y = rand(0, 100); 10. 11. // Create a PHP array and echo it as JSON 12. $ret = array($x, $y); 13. echo json_encode($ret); ?> 14. 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 15. 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. 16. /** 17. * Request data from the server, add it to the graph and set a timeout to request again 18. */ 19. function requestData() { 20. $.ajax({ 21. url: 'live-server-data.php', 22. success: function(point) { 23. var series = chart.series[0], 24. shift = series.data.length > 20; // shift if the series is longer than 20 25. 26. // add the point 27. chart.series[0].addPoint(point, true, shift); 28. 29. // call it again after one second 30. setTimeout(requestData, 1000); 31. }, 32. cache: false 33. }); } 34. Create the chart. Notice how our requestData function is initially called from the chart's load event. The initial data is an empty array. 35. $(document).ready(function() { 36. chart = new Highcharts.Chart({ 37. chart: { 38. renderTo: 'container', 39. defaultSeriesType: 'spline', 40. events: { 41. load: requestData 42. } 43. }, 44. title: { 45. text: 'Live random data' 46. }, 47. xAxis: { 48. type: 'datetime', 49. tickPixelInterval: 150, 50. maxZoom: 20 * 1000 51. }, 52. yAxis: { 53. minPadding: 0.2, 54. maxPadding: 0.2, 55. title: { 56. text: 'Value', 57. margin: 80 58. } 59. }, 60. series: [{ 61. name: 'Random data', 62. data: [] 63. }] 64. }); }); 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. 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. 因篇幅问题不能全部显示,请点此查看更多更全内容