While it is useful to display one data series, we may want to add more data to a chart. For example, we may want to compare two different sets of data over the same period of time.
In Highcharts, we can display additional data in a separate series
array. The series
arrays are just lists of data with a name. In Highcharts, this list is represented by a JavaScript array.
To get started, follow the ensuing instructions:
Define options for our chart as in the previous recipe, as follows:
var options = { chart: { type: 'bar' }, title: { text: 'Including multiple series in one chart' }, series: [{ name: 'Bar #1', data: [1, 2, 3, 4] }] };
Add a second series object as shown in the following code:
var options = { chart: { type: 'bar' }, title: { text: 'Including multiple series in one chart' }, series: [{ name: 'Bar #1', data: [1, 2, 3, 4] }, // Add a new series { name: 'Bar #2', data: [4, 3, 2, 1] }] };
Finally, render the chart using the
highcharts
function$('#container').highcharts(options)"
. This output is shown in the following screenshot:
If we want to add another series to the chart after it has been rendered, you can use the addSeries
method and pass it in the series object. We can get a reference to the chart in one of the following two ways:
Create the chart, then call
.highcharts()
with the appropriate jQuery selector, as shown in the following code:$('#container').highcharts(options); var chart = $('#container').highcharts();
When creating the chart, chain together a call to
.highcharts()
as follows:var chart = $('#container').highcharts(options).highcharts();
Using the chaining method, we can add a series as follows:
var chart = $('#container').highcharts(options).highcharts(); chart.addSeries({ name: 'Series 2', data: [4,3,2,1] });
The addSeries
method also has a few other arguments that can be passed. The addSeries
method also has optional second and third arguments that determine whether the chart should be redrawn (defaults to true
) and how the new series should be animated (defaults to true
, but we could supply an animation object that is best described in the documentation).