How To Use
Table of contents
- Installation
- How to set up the options
- Understanding axes
- Preprocessing the options
- Live charts
- Exporting module
- Freeform drawing
1. Installation
- 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.7.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 and the Prototype adapter has to be included separately. Use this code to include Highcharts with MooTools:
<script src="https://ajax.googleapis.com/ajax/libs/mootools/1.4.2/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>
and use this code to include Highcharts with Prototype:
<script src="https://ajax.googleapis.com/ajax/libs/prototype/1.7.0.0/prototype.js" type="text/javascript"></script> <script src="/js/adapters/prototype-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. - 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() { 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 calledHighcharts.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 }] }); }); - 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>
-
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. Understanding axes
Many of the examples in the Highcharts demo come with an xAxis with categories. However, it is important to understand when to use categories and when you are better off with a linear or datetime xAxis.
Categories are groups of items, like for example "Apples", "Pears" and "Oranges", or "Red", "Green", "Blue", "Yellow". These categories have that in common that there are no intermediate values (there's no sliding transition between apples and pears). Also, if you leave one category out, the user isn't able to understand what is left out. Say if you print every second color of "Red", "Green", "Blue" or "Yellow", the user won't know what colors are missing. Therefore, Highchars doesn't have automatic methods to hide categories if they become to dense on the axis. If you have problems with overlapping axis labels, try either the xAxis.labels.staggerLines option, or give the labels a rotation. If you find that you can skip category labels by the xAxis.labels.step option, chances are that you are better off using a linear or datetime axis.
An xAxis of the linear or datetime type has the advantage that Highcharts is able to determine how close the data labels should be because it knows how to interpolate. The labels will by default be placed with approximately 100px between them, which can be changed in the tickPixelInterval option. If you have predictable categories like "Item1", "Item2", "Item3" or "2012-01-01", "2012-01-02", "2012-01-03" etc., linear or datetime axis types combined with an xAxis.labels.formatter would probably be a better choice.
4. 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.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']
4.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.
- 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.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 <point> tag and load 1000 points, it will add some weight. If however you add a comma separated list of point values, it doesn't. The upside to using XML, at least for small data sets, is that you don't have to manually parse the incoming data. You can utilize jQuery's existing DOM parsing abilities to access the XML tree. We set up a live example for this at data-from-xml.htm. The data can be viewed at data.xml.
5. 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.
5.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 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 // Set the JSON header header("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); ?> - 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(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: [] }] }); });
6. 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.
6.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>
6.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.
As an ASP.NET alternative to our Java/PHP based server module, Clément Agarini has kindly shared his export module for ASP.NET.
7.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.
