How To Use
1. Installation
- Highcharts uses either jQuery or MooTools for some common JavaScript tasks.
You need to include the JavaScript files in the section of your web page *).
If you already have jQuery or MooTools included, you can skip the first one.
<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>
*) In version 1.x, Highcharts relied on excanvas.js for rendering in IE. From 2.0 IE VML rendering is build into the library. - In a
scripttag in theheadof 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() {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:
chart1 = new Highcharts.Chart({
chart: {
renderTo: 'chart-container-1',
defaultSeriesType: '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]
}]
});
});
<script type="text/javascript">
window.addEvent('domready', function() {
var chart1 = ....... - 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="chart-container-1" style="width: 100%; height: 400px"></div>
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 and only 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 demo gallery. For a full reference of the options available, see the 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 som 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 = 'chart-container'; options.chart.defaultSeriesType = 'bar'; options.series = new Array(); options.series[0] = new Object(); obtions.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: 'chart-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.seriesis an array, so it has apushmethod.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 asoptions['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' similar functions. All of the code
runs in the $(document).ready event handler. The example can be seen live at data-from-csv.htm.
- 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,Bananas John,8,4,6,5 Jane,3,4,2,3 Joe,86,76,79,77 Janet,3,16,13,15
- 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: [] }; - 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 update, remove, addSeries, addPoints
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.
- 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 // 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); // Return it in the form of a JavaScript array echo "[$x, $y]"; ?>
- Define the
chartvariable 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
- 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(eval(point), true, shift); // call it again after one second setTimeout(requestData, 1000); }, cache: false }); } - 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.
- Make sure that PHP and Java is installed on your server.
- Upload the
index.phpfile from the /exporting-server directory in the download package to your server. - In your FTP program, create directory called
tempin the same directory asindex.phpand chmod this new directory to 777 (Linux/Unix servers only). - Download Batik from http://xmlgraphics.apache.org/batik/#download. Find the binary distribution for your version of JRE
- Upload
batik-rasterizer.jarand the entirelibdirectory to a location on your web server. - In the options in the top of the index.php file, set the path to batik-rasterier.jar.
- In your chart options, set the exporting.url option to match your PHP file location.
