I want to format a reusable Highcharts tooltip dependent on a global value. (I'm using the same chart to switch between currency and numeric values: if I'm showing currency data on the chart, I want to format the tooltip as currency.)
However, this
in the Highcharts tooltip function seems to refer to the local data point only, and I don't seem to be able to pass a value in.
How do I either pass a value in, or get a global value? This is my code right now, which fails horribly:
getChartTooltip: function() {
return function(graphType) {
var prefix = (graphType === 'currency') ? '$' : ''; // Fails
return prefix + Highcharts.numberFormat(this.y, 0);
};
},
initializeChart: function() {
var graphType = 'currency';
var chartOptions = {};
chartOptions.tooltip = {
formatter: getChartTooltip(graphType)
};
// create chart, etc...
$('change-chart-type').on('click', function() {
// Try to update the tooltip formatter, fail horribly...
graphType = 'number';
chart.series[0].update({
tooltip: {
formatter: _this.getChartTooltip(graphType)
}
});
});
What's a better way to do this?
You don't need to change the tooltip.formatter
, because it's the formatter
itself who will change the tooltip
.
I would try something like :
tooltip: {
formatter: function() {
var unit = ' $',
result = this.value;
if(this.series.name == 'your_currency_serie_name'){
result += unit;
}
return result;
}
}
Where 'your_currency_serie_name'
is the name of the serie which refers to currency values.
You can set the tooltip
options in each series as well via the valueDecimals
, valuePrefix
, and valueSuffix
options. The tooltip
will then use these options for displaying the data. Live demo.
Generic setup:
...
series: [{
tooltip: {
valueDecimals: 0,
valuePrefix: '',
valueSuffix: ''
},
data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4]
}, {
tooltip: {
valueDecimals: 2,
valuePrefix: '$',
valueSuffix: ' USD'
},
data: [129.9, 171.5, 1106.4, 1129.2, 1144.0, 1176.0, 1135.6, 1148.5, 1216.4, 1194.1, 195.6, 154.4]
}]
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With