Learning Highcharts

4 (1 reviews total)
By Joe Kuan
  • Instant online access to over 7,500+ books and videos
  • Constantly updated with 100+ new titles each month
  • Breadth and depth in over 1,000+ technologies
  1. Web Charts

About this book

Highcharts is a popular web charting software that produces stunning and smooth animated JavaScript and HTML5 SVG graphs. It is among the leading web charting software in the market and has been used in many different sectors — from financial to social websites. Although it is built on top of jQuery, it is so simple to construct that you need little programming skill to create a simple web chart. Highcharts works on all modern browsers and is solely based on native browser technologies and doesn't require client side plugins like Flash or Java.

"Learning Highcharts" is a comprehensive tutorial with clear and practical examples. This book follows a step by step approach towards making artistic, presentable, or professional style charts and other types of charts that you won’t find elsewhere. It also shows you how to integrate Highcharts with other popular frameworks, such as jQuery, jQuery Mobile, and ExtJS and even how to run it on the server side.

The book starts off with an introduction to Highcharts and demonstrates usage of its rich set of options. This is followed by an introduction to each type of basic chart, beginning with simple illustrations and ending with more artistic and productive additions to the charts. The book then guides you how to use the Highcharts API and events handling which are important to build interactive applications. It then goes on to show you how to apply Highcharts onto a popular AJAX Framework or even jQuery, jQuery Mobile and Ext JS. Finally the book shows readers how to set up Highcharts running on server side.

"Learning Highcharts" aims to teach you everything you need to know about Highcharts, and take the advanced leap from Flash to JavaScript, with this extremely productive and effective Charting software available, thus helping you build basic charts and even multiple series and axes charts. The book also shows you the flexibility of Highcharts and how to create other special charts. The programming side of APIs and event handling will benefit the readers in building advanced web applications with Highcharts. The book also guides readers on how to integrate Highcharts with popular frameworks such as jQuery Mobile and Ext JS. By the end of the book, you should be able to use Highcharts to suit your web page or application needs.

Publication date:
December 2012
Publisher
Packt
Pages
362
ISBN
9781849519083

 

Chapter 1. Web Charts

In this chapter you will learn the general background of web charts. This includes a short history of how web charts used to be made before Ajax and HTML5 became the new standard. The recent advancement in JavaScript programming will be briefly discussed. Then the new HTML5 features—SVG and canvas, which are the main drive behind JavaScript charts, are introduced and demonstrated. This is followed by a quick guide on the other JavaScript graphing packages that are available on the market. Finally, an introduction of Highcharts is given, which explains the advantages of Highcharts over the other products. In this chapter we will cover the following:

  • A short history of web charting

  • The uprising of JavaScript and HTML5

  • JavaScript charts on the market

  • Why Highcharts?

    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.

 

A short history of web charting


Before diving into Highcharts, it is worth mentioning how web charts evolved from pure HTML with server-side technology to the current client side.

HTML image map (server-side technology)

This technique has been used since the early days of HTML, when server-side operations were the main drive. Charts were only HTML images generated from the web server. Before there was any server-side scripting language such as PHP, one of the common approaches was to use Common Gateway Interface (CGI), which executes plotting programs (such as gnuplot) to output the images. Later, when PHP became popular, the GD graphic module was used for plotting. One product that uses this technique is JpGraph. The following is an example of how to include a chart image in an HTML page:

<img src="pie_chart.php" border=0 align="left"> 

The chart script file— pie_chart.php—is embedded inside an HTML img tag. When the page is loaded, the browser sees the img src attribute and sends an HTTP request for pie_chart.php. As far as the web browser is concerned, it has no knowledge whether the .php file is an image file or not. When the web server (with PHP support) receives the request, it recognizes the .php extension and executes the PHP scripts. The following is the cut down JpGraph example; the script outputs the image content and streams it back as an HTTP response, in the same way as normal image content would be sent back.

// Create new graph
$graph = new Graph(350, 250);
// Add data points in array of x-axis and y-axis values
$p1 = new LinePlot($datay,$datax);
$graph->Add($p1);
// Output line chart in image format back to the client
$graph->Stroke();

Furthermore, this technology combines with an HTML map tag for chart navigation, so that when users click on a certain area of a graph, for example a slice in a pie chart, it can load a new page with another graph.

This technology has the following advantages:

  • Server-side technology, which means chart creation does not necessarily require user interaction to initiate.

  • Ideal for automation tasks, for example scheduled reports or e-mail alerts with the graph attached.

  • Doesn't require JavaScript. It is robust, pure HTML, and is light on the client.

It has the following disadvantages:

  • More workload on the server side

  • Pure HTML, a limited technology—little interactions can be put on the graphs and no animations

Java applet (client side) and servlet (server side)

Java applet enables the web browser to execute multiplatform Java Byte Code to achieve what HTML cannot do, such as graphics display, animations, and advanced user interactions. This was the first technology to extend traditional server-based work to the client side. To include a Java applet in an HTML page, HTML applet (deprecated) or object tags are used and require a Java plugin to be installed for the browser.

The following is an example of including a Java applet inside an object tag. As Java does not run on the same environment in Internet Explorer as other browsers, the conditional comments for IE were used:

<!--[if !IE]> Non Internet Explorer way of loading applet -->
<object classid="Java:chart.class" type="application/x-java-applet"
 height="300" width="550" >
<!--<![endif] Internet way of loading applet -->
  <object classid="clsid:8AD9C840..." codebase="/classes/">
  <param name="code" value="chart.class" />
  </object>
<!--[if !IE]> -->
</object>
<!--<![endif]--> 

Generally, the Java 2D chart products are built from the java.awt.Graphics2D class and the java.awt.geom package from Java Abstract Window Toolkit (AWT). Then, the main chart library allows the users to have the option of using it on a browser extending from the Applet class or running it on the server side extending from the Servlet class.

An example of a Java product is JFreeChart. It comes with 2D and 3D solutions and is free for nonprofit use. JFreeChart can be run as an applet, servlet, or standalone application. The following shows part of the code used to plot data points within an applet:

public class AppletGraph extends JApplet {
  // Create X and Y axis plot dataset and populate
  // with data.
  XYPlot xyPlot = new XYPlot(); 
  xyPlot.setDataset(defaultXYDataset);
  CombinedDomainXYPlot combinedDomainXYPlot = 
    new CombinedDomainXYPlot();
  combinedDomainXYPlot.add(xyPlot);
  // Create a jFreeChart object with the dataset 
  JFreeChart jFreeChart = new JFreeChart(combinedDomainXYPlot);
  // Put the jFreeChart in a chartPanel 
  ChartPanel chartPanel = new ChartPanel(jFreeChart);
  chartPanel.setPreferredSize(new Dimension(900,600));
  // Add the chart panel into the display
  getContentPane().add(chartPanel);
}

To run a chart application on the server side, a servlet container is needed, for example Apache Tomcat. The standard web.xml file is defined to bind a URL to a servlet:

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="server_charts" version="2.4" xmlns="..." xmlns:xsi="..."
  xsi:schemaLocation="...">
  <servlet>
    <servlet-name>PieChartServlet</servlet-name>
    <servlet-class>charts.PieChartServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>PieChartServlet</servlet-name>
    <url-pattern>/servlets/piechart</url-pattern>
  </servlet-mapping>
</web-app>

When the servlet container, such as Tomcat, receives an HTTP request with the URL http://localhost/servlets/piechart, it resolves the request into a servlet application. The web server then executes the chart servlet, formats the output into an image, and returns the image content as an HTTP response.

This technology has the following advantages:

  • Advanced graphics, animations, and user interfaces

  • Reusable core code for different deployment options—client side, server side, or standalone applications

It has the following disadvantages:

  • Applet security issues

  • If the plugin crashes, it can hang or crash the browser

  • Very CPU intensive

  • Requires Java plugin

  • Long startup time

  • Standardization problem

Adobe Shockwave Flash (client side)

Flash is widely used because it offers audio, graphics, animation, and video capabilities on web browsers. Browsers are required to have the Adobe Flash Player plugin installed. As for plotting graphs, this technique is the common choice (because there weren't many other options) before the HTML5 standard became popular.

Graphing software adopting this technology basically ship with their own exported Shockwave Flash (SWF) files. These SWF files contain compressed vector-based graphics and compiled ActionScript instructions to create a chart. In order for the Flash Player to display the graphs, the SWF file is needed to be loaded from an HTML page. To do that, an HTML object tag is needed. The tag is internally created and injected into the document's DOM by the software's own JavaScript routines.

Inside this object tag, it contains dimension and SWF path information for plotting the graph, and the graph variable data is also passed inside this tag. So, as soon as the browser sees an object tag with specific parameters, it calls the installed Flash Player to process both the SWF file and the parameters. To pass the graph's plot data from the server side to the client side's Flash Player, flashVars is embedded inside a param tag with the data type. The following is an example from Yahoo YUI 2:

<object id="yuiswf1" type="..." data="charts.swf" width="100%" height="100%">
<param name="allowscriptaccess" value="always">
<param name="flashVars" value="param1=value1&param2=value2">
</object>

This technology has the following advantage:

  • Pretty graphics and animations with rich user interactions

It has the following disadvantage:

  • Similar to applets

 

The uprising of JavaScript and HTML5


The role of JavaScript has been shifted significantly from a few simple client routines to a dominant language for creating and managing web user interfaces. The programming technique is nothing like what it was a decade ago. This is driven by a group of pioneers such as Douglas Crockford who is responsible for transforming the language for educating and making JavaScript a better language with his book JavaScript: The Good Parts, O'Reilly Media / Yahoo Press; and both Sam Stephenson, creator of Prototype JavaScript library (http://www.prototypejs.org), and John Resig, creator of JQuery library (http://jquery.com), who brought JavaScript into a framework for building more complicated web frontend software.

To give an introduction of the new programming style is beyond the scope of this book. However, throughout this book, we will see examples in jQuery (because Highcharts uses a jQuery library as the default choice and jQuery is the most popular JavaScript framework). Readers are expected to know the basics of jQuery and CSS selector syntax. Readers should also be familiar with advanced JavaScript scripting described in the book JavaScript: The Good Parts, such as prototypes, closure, inheritance, and function objects.

HTML5 (SVG and canvas)

In this section, two HTML5 technologies, SVG and canvas, are covered with examples.

SVG (Scalable Vector Graphics)

HTML5 is the biggest advancement so far in the HTML standard. The adoption of the standard is growing fast (also fuelled by Apple mobile devices, which stopped supporting Adobe Flash). HTML5 comes with many new features. Again, it is beyond the scope of this book to cover them. However, the most relevant part to web charting is Scalable Vector Graphics (SVG). SVG is an XML format for describing vector-based graphics, which is composed of components such as paths, text, shapes, color, and so on. The technology is similar to PostScript except that PostScript is a stack-based language. As implied by its name, one of the major advantages of SVG is that it is a lossless technology (same as PostScript); it doesn't suffer from any pixelation effect by enlarging the image. A reduced image size will not suffer from loss of original content.

Furthermore, the SVG can be scripted with timing animation Synchronized Multimedia Integration Language (SMIL) and event handling. SVG technology is supported by all the major browsers.

The following is a simple example of SVG code—a single curved line between two points:

<svg xmlns="http://www.w3.org/2000/svg" version="1.1">
  <path id="curveAB" d="M 100 350 q 150 -300 300 0" stroke="blue" stroke-width="5" fill="none" />
  <!-- Mark relevant points -->
  <g stroke="black" stroke-width="3" fill="black">
    <circle id="pointA" cx="100" cy="350" r="3" />
    <circle id="pointB" cx="400" cy="350" r="3" />
  </g>
  <!-- Label the points -->
  <g font-size="30" font="sans-serif" fill="black" stroke="none" text-anchor="middle">
    <text x="100" y="350" dx="-30">A</text>
    <text x="400" y="350" dx="30">B</text>
  </g>
</svg>

The preceding SVG code is executed in the following steps:

  1. Draw a path with id="curveAB" with data (d). First, move M to an absolute coordinate (100, 350), then draw a Bézier quadratic curve from the current position to (150, -300) and finish at (300, 0).

  2. Group (g) the two circle elements—"pointA" and "pointB"—with the center coordinates (100, 350) and (400, 350) respectively with a radius of 3 pixels. Then fill both circles in black.

  3. Group the two text elements A and B, started at (100, 350) and (400, 350), which display with the sans-serif font in black, and then shift along the x axis (dx) 30 pixels left and right, respectively.

The following is the final graph from the SVG script:

Canvas

Canvas is another new HTML5 standard, which is used by some JavaScript chart software. The purpose of canvas is as its name implies; you declare a drawing area in the canvas tag, then use the new JavaScript APIs to draw lines and shapes in pixels. Canvas has no built-in animation routine, so the API calls in timing sequences are used to simulate an animation. Also, there is no event handling support; developers need to manually attach event handlers to certain regions in the canvas. Hence, fancy chart animation may prove more complicated to implement.

The following is an example of canvas code, which achieves the same effect as the preceding SVG curve:

<canvas id="myCanvas" width="500" height="300" style="border:1px solid #d3d3d3;">Canvas tag not supported</canvas>
<script type="text/javascript">
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
// Draw the quadratic curve from Point A to B
ctx.beginPath();
ctx.moveTo(100, 250);
ctx.quadraticCurveTo(250, 0, 400, 250);
ctx.strokeStyle="blue";
ctx.lineWidth=5;
ctx.stroke();
// Draw a black circle attached to the start of the curve
ctx.fillStyle="black";
ctx.strokeStyle="black";
ctx.lineWidth=3;
ctx.beginPath();
ctx.arc(100,250,3, 0, 2* Math.PI);
ctx.stroke();
ctx.fill();
// Draw a black circle attached to the end of the curve
ctx.beginPath();
ctx.arc(400,250,3, 0, 2* Math.PI);
ctx.stroke();
ctx.fill();
// Display 'A' and 'B' text next to the points
ctx.font="30px 'sans-serif'";
ctx.textAlign="center";
ctx.fillText("A", 70, 250);
ctx.fillText("B", 430, 250);
</script> 

As you can see, both canvas and SVG can do the same task whereas canvas takes more instructions:

Instead of a continuous path description in SVG, a sequence of JavaScript drawing methods are called. Instead of a single tag with multiple attributes, multiple attribute setting routines are called. SVG is mostly declarative, while canvas enforces an imperative programming approach.

 

JavaScript charts on the market


There are many different chart libraries on offer on the market. It is impossible to discuss each one of them. They are open source, but some of them are short-lived in terms of not having a comprehensive set of basic charts, such as pie, line, and bar charts and they look rather unfinished. Here, a handful of commercial and open source products are discussed, including all the basic charts (and some with extras). Some of them still support the Flash plugin, which is an option for backward compatibility, the reason being SVG and canvas are not supported in older browsers. Although some of them are not free for commercial development, which is understandable, they do offer a very affordable price.

Note

See http://code.google.com/p/explorercanvas/. Many libraries use this add-on to emulate canvas prior to IE 9.

jqPlot

jqPlot is packaged with all the basic charts, as well as gauges and candlestick. The software is open source and totally free. jqPlot is based on the jQuery library and uses the canvas approach for plotting charts. This product has a very similar look and feel to Flot/Flotr. Additionally, jqPlot supports animations for column and line charts, but not pie charts, which could be the general issue on canvas approach to produce fancy implementations. In terms of documentation, it is probably the most complete, compared to other free software.

amCharts

amCharts offers a full set of charts in both 2D and 3D with other interesting charts such as radar, bubble, candlestick, and polar. All the charts look pretty and support animations. amCharts is free for commercial use but a credit label will be displayed in the upper-left corner of the charts. The only minor drawback is that the constructor API style seems a bit clumsy. Each attribute assignment has to be done either by calling a method or as an assignment statement explicitly, but not by the object specifier's style.

Ext JS 4 Charts

Ext JS is a very popular Ajax application framework developed by Sencha, a pioneer company specializing in web application development. In Ext JS 4, it comes with the pure JavaScript charts library unlike its predecessor Ext JS 3, which uses the YUI 2 Flash chart library. As the market trend is moving away from Adobe Flash, Sencha responds with a home brew charting library. Ext JS 4 covers all the basic 2D charts plus the gauge and radar charts, and all the charts support animations. The license is free for open source and noncommercial usage, and a developer license is needed for commercial development. A great benefit of Ext JS 4 charts is the integration with the comprehensive set of UI components, for example, for a chart with a storage framework, displaying/updating both the chart and the table of data with editors is very simple to do.

YUI 3 Charts

YUI 3 is another popular Ajax application framework under BSD license. YUI 3 has removed their support for Flash and implemented their own JavaScript charts. The new version comes with all the basic charts in 2D without any animation's support. However, the line charts look just above average, and the column and pie charts look plain and basic. Like Sencha's Ext JS, charts in YUI can be integrated with other components supplied by the framework.

FusionCharts

FusionCharts is probably one of the most impressive looking and has the most comprehensive charts out there in the market. Not only does it come with a full-range variety of interesting 2D charts (radar, dial, map, and candlestick) available as a separate product, but it also offers fully interactive 3D charts. All the chart animations are very professionally done. Basically, FusionCharts can be run in two modes, Flash or JavaScript. For the JavaScript mode, FusionCharts use their own extended Highcharts library to achieve the same 2D and 3D effect, and look the same as their Flash version. Although FusionCharts comes with a higher price tag, this is the only product that has the best looking charts and rotatable 3D charts.

JS Charts

JS Charts offers all the basic charts in both 2D and 3D looks. JS Charts uses the HTML5 canvas technology to render charts. The bars and lines look good with animations, however, the presentation of a pie chart is slightly behind and it offers no animation support. The product is free for noncommercial use and commercial license is on per domain basis. The constructor API is similar to amCharts done via method calls.

Flot and Flotr

Flot is an MIT licensed freeware offering 2D charts but without any animation at the time of writing. It is a canvas-based product built on the jQuery framework. The software produces nice-looking line charts but not the bar and pie charts (which require a plugin). Documentation is not very comprehensive and there are not many update activities within the product. There is also another chart package, Flotr, which is inspired by the Flot line chart style and is based on the Prototype framework. Flotr offers all the basic canvas charts with better looking bar and pie charts, and includes candlestick and radar charts. However, Flotr has even fewer activities than Flot; both products seem to be heading towards the end of their lifecycle.

 

Why Highcharts?


Although Highcharts only has the basic 2D charts, it offers very appealing and professional looking charts in the market. It is a product which stands out by paying attention to details, not only on the presentation side but also in other areas that are described later on. The product was released in late 2009 and developed by a Norwegian company called Highsoft Solutions AS, created and founded by Torstein Hønsi. Highcharts is not their first product, but by far their best selling one.

Highcharts and JavaScript frameworks

Although Highcharts is built with the JavaScript framework library, it is implemented in such a way that it doesn't totally rely on one particular framework. Highcharts is packaged with adapters, to make its interfaces to framework, pluggable.

As a result, Highcharts can be incorporated under MooTools, Prototype, or jQuery JavaScript frameworks. This empowers users without compromising their already developed product or allows them to decide on using the framework which is best suited to their projects. Highcharts uses jQuery as the default framework implementation, hence it only requires users to load the jQuery library before Highcharts.

To use Highcharts under the MooTools environment, users simply do the following:

<script src="//ajax.googleapis.com/ajax/libs/mootools/1.4.5/mootools-yui-compressed.js"></script>
<script type="text/javascript" 
        src="Highcharts-2.2.2/js/adapters/mootools-adapter.js"></script>
<script type="text/javascript" 
        src="Highcharts-2.2.2/js/highcharts.js"></script>

And to use Highcharts under Prototype, users need to do the following:

<script src="//ajax.googleapis.com/ajax/libs/prototype/1.7.1.0/prototype.js"></script>
<script type="text/javascript" 
        src="Highcharts-2.2.2/js/adapters/prototype-adapter.js"></script>
<script type="text/javascript" 
        src="Highcharts-2.2.2/js/highcharts.js"></script>  

Presentation

Highcharts strikes the right balance of look and feel. The charts themselves are visually pleasant and yet the style is simple. The default choices of color are soothing without a sharp contrast conflicting each other, which is aided by the subtle shadow and white border effects. None of the text nor the colors of the axes are in black or any dark color, which keeps the viewers' attention centered to the colored data presentation.

All the animations (initial, update, tooltip) in Highcharts are finely tuned—smooth with a gradual slowdown motion. For instance, the initial animation of the donut chart, which is a multiseries pie chart, is the most impressive one. This is the area where Highcharts is clearly better; the animations in other charts are too mechanical, too much, and sometimes off-putting.

The round corners of tooltip and legends (both inner and outer) with a simple border do not fight for the viewers' attention and nicely blend inside the chart. The following is a tooltip sample:

The following is a legend example with two series:

In a nutshell, every element in Highcharts does not compete with each other for viewers' attention; they share the load equally and work together as a chart.

License

Highcharts has free noncommercial as well as commercial licenses. The free license for personal and nonprofit purposes is Creative Commons – Attribution NonCommercial 3.0. Highcharts offers different flavors of commercial licenses for different purposes. They have a one-off single website license and, thankfully, developer licenses. For web development products, a developer license is a better model than charging in units of website basis or a very high priced OEM license because of the following reasons:

  • It is easy for the software companies to work out the math in their development plans

  • There is less worry regarding how many copies are being sold, so as to not violate the license

As usual, the developer license does not automatically grant the use of Highcharts indefinitely. The license only permits the unlimited use of all the versions released within a year from the license purchase date. Thereafter, an update license is required if developers decide to use a newer version and so on. Moreover, any condition can be negotiated for the OEM license, and most commonly, the quote is based on the number of developers on the project and the number of deployments.

Simple API model

Highcharts has a very simple API model. For creating a chart, the constructor API expects an object specifier with all the necessary settings. As for dynamically updating an existing chart, Highcharts comes with a small set of APIs. The configuration properties are described in detail in Chapter 2, Highcharts Configurations. The API calls are discussed in Chapter 7, Highcharts APIs.

Documentations

Highcharts' online documentation is one of the areas that really outshines the others. It is not just a simple documentation page to dump all the definitions and examples. It's a documentation page built with thought. Here is why.

The left-hand side of the documentation page is organized in an object structure as how you would pass it to create a chart. You can expand and collapse the object's attributes further like in a JavaScript console. This has helped the users to become familiar with the product by using it naturally.

The well thought out part of the documentation is on the right-hand side with the definitions of the attributes. Each definition comes with a description and an online demonstration for each setting linking to the jsFiddle website.

This instant jsFiddle demo invites users to explore different property values and observes the effect on the chart. Hence, the whole documentation browsing process becomes very effective and fluid.

Openness (feature request with user voice)

One unusual way of how Highcharts decides new features for every major release is via the users' voice (this is not unusual in open source project practices but it is one of the areas where Highcharts is better than the others). Users can submit new feature requests and then vote for them. The company then reviews the feature requests with the highest votes and draws up a development plan for the new features. The details of the plan are then published on the Highcharts website.

In addition, Highcharts is hosted on GitHub, an online public source control service, which allows JavaScript developers to contribute and clone their own versions.

 

Highcharts – a quick tutorial


In this section, you will see how to implement your first Highcharts graph. First, download the latest version from the Highcharts website.

Directories structure

When you unpack the downloaded ZIP file, you should see the following directories' structure under the Highcharts-2.x.x top-level directory:

The following is what each directory contains and is used for:

  • index.html: This is the demo HTML page, which is the same as the demo page on the Highcharts website, so that you can still experiment with Highcharts offline.

  • examples: This contains all the source files for the examples.

  • graphics: This contains image files used by the examples.

  • exporting-server: This is a directory for the server-side function to export charts into an image file using Batik, which is a Java-based toolkit for managing SVG content, and exporting the server is one of its usages.

  • js: This is the main directory with Highcharts code. Each JavaScript filename has two suffixes, .src.js, which contains the source code with comments in it, and .js, which is the minification of JavaScript source files.

  • adapters: This has the adapter facility for using with MooTools or Prototype modules. It contains the following files:

    • exporting.js for client-side exporting and printing functions

    • canvas-tools.js – we need to use a third-party tool, canvg, to support Android 2.x, as the native browser has no SVG support but can display the canvas

  • themes: This has a set of JavaScript files pre-built with settings such as background colors, font styles, axis layouts, and so on. Users can load one of these files in their charts for different styles.

All you need to do is move the top-level Highcharts-2.x.x/js directory inside your web server document's root directory.

To use Highcharts, you need to include Highcharts-2.x.x/js/highcharts.js and a jQuery library in your HTML file. The following is an example showing the percentage of web browsers' usage for a public website. The example uses the minimal configuration settings for getting you started quickly. The following is the top half of the example:

<!DOCTYPE HTML>
<html>
  <head>
    <meta http-equiv="Content-Type" 
          content="text/html; charset=utf-8">
    <title>Highcharts First Example</title>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <script type="text/javascript" 
        src="Highcharts-2.2.2/js/highcharts.js"></script>

We use the Google public library service to load the jQuery library Version 1.7.1 before loading the Highcharts library.

The second half of the example is the main Highcharts code, as follows:

<script type="text/javascript">
    $(document).ready(function() {
        var chart = new Highcharts.Chart({
            chart: {
                renderTo: 'container',
                type: 'spline'
            },
            title: {
                text: 'Web browsers statistics'
            },
            subtitle: {
                text: 'From 2008 to present'
            },
            xAxis: {
                categories: [ 'Jan 2008', 'Feb', .... ],
                tickInterval: 3
            },
            yAxis: {
                title: {
                    text: 'Percentage %'
                },
                min: 0
            },
            plotOptions: {
                series: {
                    lineWidth: 2
                }
            },
            series: [{
                name: 'Internet Explorer',
                data: [54.7, 54.7, 53.9, 54.8, 54.4, ... ]
            }, {
                name: 'FireFox',
                data: [36.4, 36.5, 37.0, 39.1, 39.8, ... ]
            }, {
                // Chrome started until late 2008
                name: 'Chrome',
                data: [ null, null, null, null, null, null, 
                        null, null, 3.1, 3.0, 3.1, 3.6, ... ] 
            }, {
                name: 'Safari',
                data: [ 1.9, 2.0, 2.1, 2.2, 2.4, 2.6, ... ]
            }, {
                name: 'Opera',
                data: [ 1.4, 1.4, 1.4, 1.4, 1.5, 1.7, ... ]
            }]
        });
    });
</script>
  </head>
  <body>
  <div>
    <!-- Highcharts rendering takes place inside this DIV --> 
    <div id="container"></div>
  </div>
</body>
</html>

The spline graph is created via an object specifier that contains all the properties and series data required. Once the chart object is created, the graph is displayed in the browser. Within this object specifier, there are major components corresponding to the structure of the chart.

var chart = new Highcharts.Chart({ 
    chart: {
        ...
    },
    title: '...'
    ... 
});

The renderTo option instructs Highcharts to display the graph onto the HTML <div> element with 'container' as the ID value, which is defined in the HTML <body> section. The type option is set to the default presentation type as 'spline' for any series data, as follows:

chart: {
    renderTo: 'container',
    type: 'spline'
}

Next is to set title and subtitle, which appears at the center part at the top of the chart:

title: {
   text: 'Web browsers ... '
},
subtitle: {
   text: 'From 2008 to present'
},

The categories option in the xAxis property contains an array of x axis labels for each data point. Since the graph has at least 50 data points, printing each x axis label will make the text overlap each other. Rotating the labels still results in the axis looking very packed. The best compromise is to print every third label, (tickIntervals: 3) which causes the labels to be nicely spaced out from each other.

Note

For the sake of simplicity, we use 50 entries in xAxis.categories to represent the time. However, we will see a more optimal and logical way to display date time data in the next chapter.

xAxis: {
   categories: [ 'Jan 2008', 'Feb', .... ],
   tickInterval: 3
},

The options in yAxis are to assign the title of the y axis and set the minimum possible value to zero, otherwise Highcharts will display a negative percentage range along the y axis, which is unwanted for this dataset.

yAxis: {
     title: {
         text: 'Percentage %'
     },
     min: 0
},

The plotOptions property is to control how each series is displayed according to its type (line, pie, bar, and so on). The plotOptions.series option is the general configuration applied to all the series type instead of defining each setting inside the series array. In this example, the default lineWidth for all the series is set to 2 pixels wide, as follows:

 plotOptions: {
    series: {
        lineWidth: 2
    }
},

The series property is the heart of the whole configuration object, which defines all the series data. It is an array of the series configuration objects. For this example, the name option is the name of the series that appears in the chart legend and tooltip. The data is an array of y axis values, which has the same length as the xAxis.categories array to form (x,y) data points.

series: [{
     name: 'Internet Explorer',
     data: [54.7, 54.7, 53.9, 54.8, 54.4, ... ]
}, {
     name: 'FireFox',
     data: [36.4, 36.5, 37.0, 39.1, 39.8, ... ]
}, {

The following screenshot shows how the final Highcharts should look on a Safari browser:

The following screenshot shows how it should look on an Internet Explorer 9 browser:

The following screenshot shows how it should look on a Chrome browser:

The following screenshot shows how it should look on a Firefox browser:

 

Summary


Web charting has been around since the early days of HTML, emerging from server-side technology to client-side. During this period, several solutions have been adopted to work around the shortcomings of HTML. Now, with the new HTML5, which is rich in features, web charting has come back to HTML and this time it is for good, with the aid of unleashed JavaScript.

A number of JavaScript chart products were mentioned in this chapter.. Among these, Highcharts emerges with a distinct graphical style and smooth user interactions.

In the next chapter, we will explore the Highcharts configuration object in greater detail with plenty more examples. The configuration object is the core part of the product that the structure serves as the common prototype for all the charts.

About the Author

  • Joe Kuan

    Joe Kuan was born in Hong Kong and continued his education in the UK from secondary school to university. He studied computer science at the University of Southampton for his BSc and PhD. After finishing his education, he worked with different technologies and industries in the UK. Currently, he is working for iTrinegy—a company specializing in network emulation, profiling, and performance monitoring. He enjoys working on a variety of projects and applying different programming languages. Part of his role is to develop frontend data and present complex network data in stylish and interactive charts. He has adopted Highcharts in his company products since the early version 2. Since then, he has been contributing blogs (joekuan.wordpress.com) and software (joekuan.org) on Highcharts, Highstocks, and Highmaps. In December 2012, he published his first book, Learning Highcharts, Packt Publishing, which is a comprehensive book on Highcharts covering tutorials, examples, tricks, and tips.

    Browse publications by this author

Latest Reviews

(1 reviews total)
The book is a good reference work for Highcharts. However, I already learned most of the Highstock (slightly different) tricks on my own before the book arrived. My son may still use it for school work.