We've already seen that tooltips can add useful behavior to our charts; however, we are not merely limited to changing colors or text in the tooltip. It is possible to access more data than just what Highcharts provides.
To get started, follow the ensuing instructions:
Create or make available a set of additional data that we would like to use in our tooltips as follows:
var altName = ["apple", "banana", "pear"];
Define options for our chart, including our series and its additional data, as shown in the following code:
var options = { chart: { type: 'bar' }, title: { text: 'Adding extra content to tooltips' }, series: [{ data: [{ 'x': 1, 'y': 4, 'category': 'Apple' }, { 'x': 2, 'y': 3, 'category': 'Pear' }, { 'x': 3, 'y': 2, 'category': 'Banana' }] }] };
Access our desired fields in the
formatter
function viathis.point.options
as shown in the following code:var options = { // ... tooltip: { formatter: function() { return 'We have ' + this.y + ' ' + this.point.options.category + 's' } } }
The following is the output chart:
Highcharts supports multiple data formats. Earlier, we were using its most basic format—an array of numeric data. However, as in this example, we have seen that the data
array can be more complex. A data series can support two other formats—an array of objects with named values (as we used previously) and an array of the [x,y]
coordinates, as you can see in the following code:
var options = { // ... series: { data: [ [1,1], [2,2], [3,3] ] } }
When we specify data as an array of objects, we can access the information about the individual points via this.point.options
. Since the formatter
function is just a JavaScript function, we can do whatever we might normally do inside a JavaScript function, such as displaying our additional information.