Home Data Learning Highcharts 4

Learning Highcharts 4

By Joe Kuan
books-svg-icon Book
eBook $28.99 $19.99
Print $48.99
Subscription $15.99 $10 p/m for three months
$10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
BUY NOW $10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
eBook $28.99 $19.99
Print $48.99
Subscription $15.99 $10 p/m for three months
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
  1. Free Chapter
    Web Charts
About this book
Publication date:
January 2015
Publisher
Packt
Pages
478
ISBN
9781783287451

 

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 advances in JavaScript programming will be briefly discussed. Then, SVG support and the new HTML5 feature canvas, the main drive behind JavaScript charts, are introduced and demonstrated. This is followed by a quick guide to the other JavaScript graphing packages that are available on the market. Finally, we are introduced to Highcharts and will explain the advantages of using Highcharts over other products. In this chapter, we will cover the following topics:

  • A short history of web charting

  • The rise of JavaScript and HTML5

  • JavaScript charts on the market

  • Why Highcharts?

 

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 were any server-side scripting languages such as PHP, one of the most common approaches was to use Common Gateway Interface (CGI), which executes plotting programs (such as gnuplot) to output 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 in 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 of 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 a 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:

  • 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 side.

It has the following disadvantages:

  • More workload on the server side

  • Pure HTML and a limited technology—few interactions can be put on the graphs and none on the animations

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

A Java applet enables the web browser to execute multiplatform Java bytecode 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's 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 in the same environment in Internet Explorer as in 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 utilize it in a browser, extending from the Applet class, or to run 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 a Java plugin

  • Long startup time

  • Standardization problems

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 was a common choice (because there weren't many other options) before the HTML5 standard became popular.

Graphing software adopting this technology ships with its 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 has 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 is dimension and SWF path information for plotting the graph. 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 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 advantages:

  • Pretty graphics and animations with rich user interactions

It has the following disadvantages:

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

  • Very CPU-intensive

  • Long startup time

  • Standardization problems

 

The rise of JavaScript and HTML5


The role of JavaScript has shifted significantly from a few simple client routines to a dominant language to create and manage web user interfaces. The programming technique has moved towards object-oriented with the introduction of function object, prototype, and closure. This was driven by a group of pioneers such as Douglas Crockford, who was responsible for transforming the language to educate and make JavaScript a better language with his book JavaScript: The Good Parts, O'Reilly Media / Yahoo Press Others include Sam Stephenson, creator of the Prototype JavaScript library (http://www.prototypejs.org), and John Resig, creator of the JQuery library (http://jquery.com), who brought JavaScript into a framework for building more complicated frontend web software.

It is beyond the scope of this book to give an introduction to this new programming style. Readers are expected to know the basics of jQuery and CSS selector syntax, which are used in some of the chapters. Readers should also be familiar with the advanced JavaScript scripting described in the book JavaScript: The Good Parts, O'Reilly Media / Yahoo Press, such as prototypes, closure, inheritance, and function objects.

HTML5 (SVG and Canvas)

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

SVG

HTML5 is the biggest advance 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). 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 that 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 (the same as PostScript): it doesn't suffer from any pixelation effects by enlarging the image. A reduced image size will not suffer from loss of original content.

Furthermore, SVG can be scripted with timing animation Synchronized Multimedia Integration Language (SMIL) and event handling. Apart from IE, this SVG technology is supported by all mainstream browsers, http://caniuse.com/#feat=svg-smil.

The following is a simple example of SVG code showing 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 that is used by some JavaScript chart software packages. The purpose of Canvas is as its name implies; you declare a drawing area on the canvas tag, then use the new JavaScript APIs to draw lines and shapes in pixels. This is the distinct difference between the two techniques: Canvas is pixel-based, whereas SVG is vector-based. Canvas has no built-in animation routine, so API calls in timed sequences are used to simulate an animation. Also, there is no event-handling support, so developers need to manually attach event handlers to certain regions on the canvas. Fancy chart animation may prove more complicated to implement.

The following is an example of Canvas code that 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, but Canvas requires more instructions:

Instead of a continuous path description in SVG, a sequence of JavaScript drawing methods is called. The preceding Canvas code follows these steps to draw the curve:

  • In the preceding example, it first calls beginPath to start a path in the canvas, then issues the moveTo call to move the path starting point to the coordinate (100, 250) without creating a line. The quadraticCurveTo method creates the curve path from the moveTo location to the top of the curve and the end point, which is (400, 250). Once the path is set up, we set up the stroke properties before calling the stroke method to draw the line along the path.

  • We call beginPath to reset to a new path to draw and invoke the arc method to create a tiny circular path at both the start and end coordinates of the curve path. Once we have set up the stroke and fill styles, we call the fill and stroke routines to fill it black, to act as a coordinate marker.

  • Finally, we set up the font properties and create the text A and B by calling fillText with the position near the coordinate markers.

In a nutshell, instead of a single tag with multiple attributes as in SVG, Canvas adopts multiple attribute-setting routines. SVG is mostly declarative, while Canvas enforces an imperative programming approach.

 

JavaScript charts on the market


It would be unimaginable to program a chart by hand-coding in SVG or Canvas. Fortunately, there are many different chart libraries on offer on the market. It is impossible to discuss each one of them.

Tip

We have omitted some of the products mentioned in the first edition of this book, due to a lack of competitive edge.

The chart libraries 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 backwards-compatibility because SVG and canvas are not supported in older browsers. Although some of them are not free for commercial development, which is understandable, they are very affordable.

Note

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

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 presentation of the charts looks nice and the animations are fully customizable. The default animations, compared to Highcharts, seems slightly overdone.

Ext JS 5 charts

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

In Ext JS 5, the charting library has been completely restructured. Appearance is a major step forward compared to Ext JS 4: the charts look much more professionally done and on a par with other competitors. Although the Ext JS 5 chart layout, color, and animations may not be as stylish and smooth as Highcharts, it is a close call and still well-received.

Data Driven Documents

Data Driven Documents (D3) is the most widely-used charting library. It was created by Bostock et al., much improved from their prior academic research work on Protovis.

Note

Bostock, Michael; Ogievetsky, Vadim; Heer, Jeffrey (October 2011), D3: Data-Driven Documents, IEEE Transactions on Visualization and Computer Graphics, IEEE Press.

The principle of D3 is pretty unique, in that it focuses on transformation in document elements. In other words, it is a decorative framework to manipulate selected elements, known as selections, through a myriad of APIs. These APIs allow users to join the selections with chart data and style them like CSS or apply specific effects. This approach enables D3 to create a wide variety of impressive charts with animations that other products cannot produce. It is an ideal tool for plotting specific scientific graphs, or graphs that require complex data visualization presentation, such as Hierarchical Edge Bundling.

The software is free for commercial use and has attracted a large user base and contribution from user communities, especially from the academic sector.

Due to its highly programmable and comparatively low-level approach, it requires a much steeper learning curve that may not appeal to less technical users or developers looking for a chart-ready solution on a production level. As for constructing 3D charts in D3, it can be a challenging task. Although D3 trumps in performance, control, and presentation, it is not for everyone.

FusionCharts

FusionCharts is probably one of the most impressive-looking tools, and has the most comprehensive range of charts on the market. Not only does it come with a full 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. FusionCharts can be run in two modes: Flash or JavaScript. Although FusionCharts comes with a higher price tag, it offers the best looking charts bundled with rotatable, animated 3D charts in column, pie, funnel, and pyramid series.

Raphaël

Raphaël is another free graphics library. It supports both SVG and VML for earlier browsers. It is designed like a generic graphics library, handling SVG elements, but it can be used as a charting solution. The software offers APIs to create a Canvas-like object, paper, that users can then create basic shapes or line SVG elements in. The API construct is somewhat similar to D3 in the sense that it can bind data into elements and manipulate them, but with rather more primitive methods, whereas D3 is a data-centric solution. The documentation is basic and it has a smaller user community. Like D3, it requires more effort to program a presentable chart than Highcharts and is not an ideal choice for 3D chart solutions.

 

Why Highcharts?


Highcharts offers very appealing and professional-looking 2D/3D charts on the market. It is a product that stands out by paying attention to details, not only on the presentation side, but also in other areas that are described later on. It was developed by a Norwegian company called Highsoft AS, created and founded by Torstein Hønsi, and released in late 2009. Highcharts is not their first product, but is 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 frameworks pluggable.

As a result, Highcharts can be incorporated with MooTools, Prototype, or jQuery JavaScript frameworks. Highcharts also has a standalone framework for those who write in pure JavaScript. This empowers users without compromising their already-developed product, or allows them to decide to use the framework that is best suited for their projects. Users who develop their web charting applications in jQuery are only required to load the jQuery library before Highcharts.

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

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

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

<script src="http://ajax.googleapis.com/ajax/libs/prototype/1.7.1.0/prototype.js"></script>
<script type="text/javascript" 
        src="http://code.highcharts.com/adapters/prototype-adapter.js"></script>
<script type="text/javascript" 
        src="http://code.highcharts.com/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 and don't conflict with each other, 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 viewer's attention centered on the colored data presentation. The following is an example of a Highcharts representation:

All the animations (initial, update, tool tip) in Highcharts are finely tuned: smooth with a gradual slowdown motion. The initial animation of the donut chart, which is a multi-series pie chart, is the most impressive one. This is the area in which Highcharts is clearly better. The animations in other charts are too mechanical, too much, and sometimes off-putting:

The round corners of tool tips and legends (both inner and outer) with a simple border do not fight for the viewer's attention and nicely blend into the chart. The following is a tool tip sample:

The following is a legend example with two series:

In a nutshell, each element in Highcharts does not compete with others for the viewer's attention, so 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 license for different purposes. They have a one-off single website license and, thankfully, a developer license. For web development products, a developer license is a better model than charging in units of website use or a very high-priced OEM license because of the following reasons:

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

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

As usual, a 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, a brand new license is required if developers decide to use a newer version. Moreover, any condition can be negotiated for the OEM license, and the quote is usually based on the number of developers on the project and the number of deployments.

Simple API model

Highcharts has a very simple API model. To create a chart, the constructor API expects an object specifier with all the necessary settings. To dynamically update 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 10, Highcharts APIs.

Documentations

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

The left-hand side of the documentation page is organized in an object structure, as you would pass it to create a chart. You can further expand and collapse the object's attributes as in a JavaScript console. This helps 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 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 observe the effect on the chart, so the whole documentation-browsing process becomes very effective and fluid.

Openness (feature request with user voice)

One important way that Highcharts decides new features for every major release is via the users' voice (this is not unusual in open source projects, but it is one of the areas in which Highcharts is better than others). Users can submit new feature requests and then vote for them. The company then reviews the feature requests with the most votes and draws up a development plan that includes 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. Assuming that we want to run Highcharts from our local web server, first download the latest version from the Highcharts website: http://www.highcharts.com/download.

Alternatively, we can load the library via the Content Delivery Network (CDN), as follows:

<script type="text/javascript" 
        src="http://code.highcharts.com/highcharts.js"></script>

For debugging, highcharts.src.js is also available from the CDN.

Directory structure

When you unpack the downloaded ZIP file, you should see the following directory structure under the Highcharts-4.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 experiment with Highcharts offline.

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

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

  • gfx: This contains an image file required to produce the radial gradient effect for browsers that only support VML.

  • exporting-server: This directory contains three main components: a Java implementation of the online export server, a PhantomJs toolkit to run Highcharts on the service side, and server script to service the chart export function using Batik. This directory is useful for users who need to set up their own internal export service or run Highcharts as a server process. See Chapter 14, Server-side Highcharts and Chapter 15, Highcharts Online Services and Plugin.

  • js: This is the main directory for Highcharts code. Each JavaScript filename has two suffixes: .src.js, which contains the source code with comments in it, and .js, which is the minified version of the JavaScript source file. The highcharts.js file contains the core functionality and the basic chart implementations, highcharts-3d.js is the 3D charts extension, and highcharts.more.js contains additional series such as polar, gauge, bubble, range, waterfall, errobar, and boxplot. Highcharts-all.js lets users provide all the chart series in their application.

  • adapters: This contains the default adapter standalone-framework in source and compressed format.

  • modules: Since the last edition, Highcharts has created a number of plugin modules such as solid-gauge, funnel, exporting, drilldown, canvas-tools and so on. This directory contains these plugins.

    Note

    A third-party tool, canvg, supports Android 2.x, as the native browser has no SVG support but can display the canvas.

  • themes: This has a set of JavaScript files prebuilt 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-4.x.x/js directory inside your web server document's root directory.

To use Highcharts, you need to include Highcharts-4.x.x/js/highcharts.js library in your HTML file. The following is an example showing the percentage of web browser 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="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2 /jquery.min.js"></script>
    <script type="text/javascript" 
        src="Highcharts-4.0.4/js/highcharts.js"></script>

We use the Google public library service to load the jQuery library version 1.8.2 before loading the Highcharts library. At the time of writing, the latest jQuery version is 2.1.1 and the Highcharts system requirement for jQuery is 1.8.2.

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

<script type="text/javascript">
var chart;
    $(document).ready(function() {
        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 appear in the center 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. Rotating the labels still results in the axis looking very packed. The best compromise is to print every third label, (tickIntervals: 3), which makes the labels nicely spaced out from each other.

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 and 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 not wanted for this data set:

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 types instead of defining each setting inside the series array. In this example, the default linewidth for every series is set to 2-pixels wide, as follows:

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

The series property is the heart of the whole configuration object that defines all the series data. It is an array of the series object. The series object can be specified in multiple ways. For this example, the name is the name of the series that appears in the chart legend and tool tip. The data is an array of y-axis values that have 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, ... ]
}, {

Tip

Downloading the example code

You can download the example code files from your account at http://www.packtpub.com for all the Packt Publishing books you have purchased. 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.

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

The following screenshot shows how it should look on the Internet Explorer 11 browser:

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

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

 

Summary


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

A number of JavaScript chart products were mentioned in this chapter. Among these, Highcharts emerged with a distinct graphical style and smooth user interactions. We also went through a simple chart example to experience how quick and easy it is to create our very first Highcharts chart.

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 (3 reviews total)
It was a lot easier to use than other competitors.
****** service. I have been waiting to receive my invoice for one week now. I have emailed customercarepacktpub.com several times!
es una gran obra cubre los temas de una forma detallada lo recomiendo
Learning Highcharts 4
Unlock this book and the full library FREE for 7 days
Start now