A simple Highcharts example
In this example, we will create a basic column chart to show the GDP of the European Union from the year 2009 through 2013.
Let's start by creating a blank HTML file and then including jQuery and highcharts.js
in the footer:
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Highcharts Essentials</title> </head> <body> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="js/highcharts.js"></script> </body> </html>
Tip
Downloading the example code
You can download the example code files for all Packt books you have purchased from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.
We have included Version 1.11.1 of jQuery from the Google CDN.
In the next step, we will create a container for our chart with id
set to highcharts_01
:
<div id="highchart_01" style="width: 600px; height: 450px;"></div>
We also gave the container element some basic CSS styles.
Having included the required JavaScript files and created the container element, we can now initialize Highcharts in a self-executing anonymous function, as shown in the following code:
(function() { $( '#highchart_01' ).highcharts({ title: { text: 'GDP of European Union' }, chart: { type: 'column' }, xAxis: { title: { text: 'Years' }, categories: ['2009', '2010', '2011', '2012', '2013'] }, yAxis: { title: { text: 'GDP' } }, series: [ { name: 'GDP', data: [-4.5, 2.0, 1.6, -0.4, 0.1] } ] }); })();
Refresh the page and you will be presented with a clean column chart, as shown in the following screenshot:
We first referenced our container element with jQuery, $('#highcharts_01')
, and invoked the Highcharts function passed with a configuration object. The hierarchy of this configuration object is pretty simple. Each component of the configuration object corresponds to the structure of the chart.
We first set the title by setting the text
property of title
to GDP of European Union
, and it appeared at the top of the chart. Then, we specified the type of chart we are rendering by passing column
as the value to the type
property of the chart.
The next two properties correspond to the axes of the chart, that is, the x axis and y axis. We specified the title of both axes the same way we did for the chart title. The years from 2009 through 2013 were specified as an array of categories
on the x axis. These years appear at the bottom of the chart below the x axis.
Finally, the data to be plotted was passed to the series
component. This data was passed in the form of an array with each element corresponding to the categories
element as passed for the x axis.