[EDIT] I ended up solving it as I was writing this question, so see below for the answer.
I have a graph that has time periods on the x-axis, and scores on the y-axis, and at each point I'd like the tooltip to give the difference in y values between the current point and the previous one (within the same series).
Reproducible example:
library(highcharter)
hchart(df,
type="line",
hcaes(x = period, y = value, group = group)
) %>%
hc_tooltip(pointFormat = "Score: {point.y} ({previous.point.y})")
Ideally, on hovering for example over the second point for series B, I'd like it to say Score: 5 (+1)
. This will probably require some formatter=JS()
JavaScript instead of just pointFormat
, but not sure how to do that.
Courtesy of this related answer, I managed to access all y values, after which I figured out that using this.point.x
allows us to hone in on specific y values. Here's the JS:
function () {
if (this.point.x == 0) { // there's no previous point, so set to '0'
var thisDiff = 0;
} else { // use 'this.point.x' to get current position, and do '-1' to get previous position
var thisDiff = ( this.series.points[this.point.x].y - this.series.points[this.point.x - 1].y );
if (thisDiff > 0) {
thisDiff = '+' + thisDiff; // pretty print a '+' sign if difference is positive
}
}
var s = '<b>Series ' + this.series.name + ', period ' + this.point.name + ': </b>';
s += 'mean score ' + this.point.y + ' (' + thisDiff + ')';
return(s);
}
To get it to work in highcharteR
we just need to wrap this in quotation marks and pass to hc_tooltip(formatter = JS()