Recipe 18Creating Charts and Graphs with Highcharts

Problem

Our sales team has developed an affiliate program for our company’s shopping site. We’ve been tasked with developing an interface for our affiliates, and we want to show their data in a visual and attractive way. However, we need to ensure that these charts are viewable on mobile devices as well as desktops.

Ingredients

  • jQuery

  • Highcharts[43]

  • QEDServer (for our test server)[44]

Solution

The Highcharts JavaScript library lets us easily create interactive and readable charts and graphs. It works across platforms, and since it runs on the client’s machine, it doesn’t require any special configuration on our servers. The interface built into Highcharts is highly interactive and customizable, letting us present data in a number of ways. In this recipe, we’ll build and customize a simple chart and then build a more complex one using some remote data.

Building a Simple Chart

Let’s create a simple pie chart so you can get acquainted with Highcharts and its various options. First, we build a simple HTML document and include the necessary JavaScript files. We also add a <div> tag, which Highcharts will use to render the chart on our page:

highcharts/example_chart.html
 
<!DOCTYPE html>
 
<html​ lang=​"en"​​>
 
<head>
 
<meta​ charset=​"utf-8"​​>
 
<title>​Example Pie Chart​</title>
 
</head>
 
<body>
 
<div​ id=​"pie_chart"​​>​​</div>
 
 
<script
 
src=​"http://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"​​>
 
</script>
 
<script
 
src=​"http://cdnjs.cloudflare.com/ajax/libs/highcharts/4.1.5/highcharts.js"​​>
 
</script>

All the magic is done by creating a new instance of the Highcharts.Chart class and passing it some options. Highcharts has many options for configuring a chart, and this configuration can quickly get long and unwieldy. To keep it simple, we create a variable called chartOptions and set some values on it that Highcharts expects. For this simple chart we add a new <script> block to the HTML page rather than putting the code in a separate file:

highcharts/example_chart.html
 
<script>
 
(​function​($, Highcharts){
 
var​ chartOptions = {};
 
 
chartOptions.chart = { renderTo: ​"pie_chart"​ };
 
chartOptions.title = { text: ​"A sample pie chart"​ };
 
 
chartOptions.series = [{
 
type: ​"pie"​,
 
name: ​"Sample chart"​,
 
data: [
 
[​"Section 1"​, 30],
 
[​"Section 2"​, 50],
 
[​"Section 3"​, 20]
 
]
 
}];
 
var​ chart = ​new​ Highcharts.Chart(chartOptions);
 
 
})(jQuery, Highcharts);
 
</script>

The first value we set is a chart property that contains information about the chart itself. This is where we pass the ID of the <div> we created earlier. Then we set a title for the chart with some sample text. Finally, the series property is an array that contains an object for each type of chart you want to render. Highcharts allows us to pass any number of objects that will be rendered on top of one another. Each object defines a chart type, a name, and a dataset. The format of this data changes depending on the type of chart we’re using. For the pie chart, the data is a two-dimensional array in which the inner arrays are pairs of X and Y data.

With just a few lines of code, we have a chart that looks like the following figure:

images/highcharts/example_chart.png

Let’s go a little further now and explore some additional options to customize our chart.

Customizing Our Chart’s Appearance

Highcharts supports pie graphs, line graphs, area graphs, and scatter plots, and the extensibility of the graph types lets us create any number of more interesting graphs.

Consider our chartOptions variable from before. We can define a property on it called plotOptions, which is an object containing a number of settings for modifying how the graph is drawn. Let’s define some options on our pie chart from earlier.

We can set options for all charts by defining them in the series property on our chartOptions object, but we can also define options for each chart type. Let’s customize our pie chart by changing the appearance of the labels that point to each section of the chart. We add this new code right before we render the chart:

highcharts/example_chart.html
*
var​ pieChartOptions = {
*
dataLabels: {
*
style: { fontSize: 20 },
*
connectorWidth: 3,
*
formatter: ​function​() {
*
var​ label = this.point.name + ​" : "​ + this.percentage + ​"%"​;
*
return​ label;
*
}
*
}
*
};
*
*
chartOptions.plotOptions = { pie: pieChartOptions };
 
 
var​ chart = ​new​ Highcharts.Chart(chartOptions);

We first increase the font size to make it more visible. Then we increase the connector width to match the font size. Lastly, we create a function that returns a newly formatted label with our desired information. The default label shows only the point name, so we change it to show the percentage as well. Our finished chart looks like the following figure:

images/highcharts/finished_pie.png

The plotOptions property has a ton of options; refer to the Highcharts documentation on the plotOptions property to see them all.[45]

Now that we know how to create and configure a simple chart, let’s use Highcharts to model our affiliate data.

Modeling the Affiliate Datasets

Our affiliate program tracks quite a bit of data, including the customer’s name, age, and location. This kind of information is useful for profiling customers and making assumptions about how to market products. It’s our job to transform this raw data into a graph that our marketing folks can quickly analyze before they dig into the hard data.

We want our users to be able to glance at the data and understand how old the customers are. Let’s use a bar graph so that it’s easy to see the mean and the most frequent value. We’ll create something that looks like the following figure:

images/highcharts/affiliate_graph.png

To get started, let’s create a new HTML document with jQuery and Highcharts included in it. We’ll be working with JSON data and Ajax requests, so fire up QEDServer and place this new HTML file in the public directory of your QEDServer installation:

highcharts/affiliates.html
 
<!DOCTYPE html>
 
<html​ lang=​"en"​​>
 
<head>
 
<meta​ charset=​"utf-8"​​>
 
<title>​Affiliate Customer Data​</title>
 
</head>
 
 
<body>
 
<div​ id=​"customer_data"​​>​​</div>
 
 
<script
 
src=​"http://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"​​>
 
</script>
 
<script
 
src=​"http://cdnjs.cloudflare.com/ajax/libs/highcharts/4.1.5/highcharts.js"​​>
 
</script>
 
</body>
 
</html>

Within this file, we create a <script> block and set up our new instance of the Highcharts.Chart class. Let’s set a few simple options, including the chart’s title and the target element on our page where the chart will go:

highcharts/affiliates.html
 
<script>
 
 
(​function​($, Highcharts) {
 
var​ options = {
 
chart: { renderTo: ​"customer_data"​ },
 
title: { text: ​"Customer Data"​ },
 
credits: { enabled: false }
 
};
 
 
 
})(jQuery, Highcharts);
 
</script>

Now that our document is ready to go, let’s do some work with our data.

Showing the Customer Data

Normally, we’d get our customer data from a back-end system, but for the purpose of this recipe, we’ve created some sample data you can use. You’ll find it in the book’s source code, which you can download from the book’s website.[46] You’ll want the highcharts/sample_data/customer_data.json file.

Or you can create the file yourself, using something like this:

 
{
 
"customers": [
 
{ "name": ​"Adrienne Sargent"​, "age": 20 },
 
{ "name": ​"Stella Albin"​, "age": 55 },
 
{ "name": ​"Dolores Krauss"​, "age": 28 },
 
{ "name": ​"Jerry Ayala"​, "age": 34 },
 
{ "name": ​"Keith Shuman"​, "age": 35 },
 
{ "name": ​"Timothy Navarra"​, "age": 33 },
 
{ "name": ​"Norman Tanaka"​, "age": 36 }
 
]
 
}

Our index.html page and our data file must be hosted on the same web server. Remember that we can’t just pull in regular JSON data from a remote server, because of the web browser’s security restrictions. So place this sample data file in a folder called sample_data within the public folder that QEDServer uses. This way, QEDServer can serve it from http://localhost:8080/sample_data/customer_data.json, and our page can consume it properly.

To show the ages in a bar graph, we need to pair an age with the number of times it occurs. Right now, we have only a list of ages. Let’s write some JavaScript to collect the ages and sum up the frequencies. We make a request to get our customer data and do all our work inside of the success callback, which is invoked when we get data back from our Ajax request:

highcharts/affiliates.html
 
$.getJSON(​'sample_data/customer_data.json'​, ​function​(data) {
 
var​ ages = [];
 
 
$.each(data.customers, ​function​(index, customer) {
 
if​ (​typeof​ ages[customer.age] === ​"undefined"​) {
 
ages[customer.age] = 1;
 
} ​else​ {
 
ages[customer.age] += 1;
 
}
 
});
 
 
var​ age_data = [];
 
 
$.each(ages, ​function​(index, e) {
 
if​ (​typeof​ e !== ​"undefined"​) {
 
age_data.push([index, e]);
 
}
 
});
 
});

Here we use an array to store some intermediate data. The ages array uses ages as indexes and stores the number of occurrences for that age. Then we look through and collect ages that exist in the array to map them to the two-dimensional array that Highcharts needs. Now that we have our data in the correct format, let’s render our chart:

highcharts/affiliates.html
 
options.series = [{
 
type: ​"column"​,
 
name: ​"Customer Ages"​,
 
data: age_data
 
}];
 
 
var​ chart = ​new​ Highcharts.Chart(options);

Now with our final chart rendered, we can easily see the most frequently occurring ages for our customers.

Further Exploration

Highcharts is a powerful JavaScript library. In this recipe, we built simple to complex charts that only begin to take advantage of the number of available options. The Highcharts reference[47] is a great way to learn what Highcharts is capable of. We recommend taking a look at the documentation and considering what options you would like to use in future projects. Also, the documentation includes a link to an example of most of the available options on JSFiddle.net.[48]

Also See

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.142.119.114