3
votes

Using Joshua Kunt's Highcharter R package, I'm trying to add a custom tooltip and format numbers so thousands have a comma separator. The Y axis and tooltips format correctly if I don't customize the tooltip, when I use the following code:

snow <- read.csv("https://gist.githubusercontent.com/smach/d4188d200b465cba822405c323f1501c/raw/58c3785c34304ccc5dbcef632d3acb9d6dbad40c/BosChiNYCsnowfalls.csv", stringsAsFactors = FALSE)
library("highcharter")

hcoptslang <- getOption("highcharter.lang")
hcoptslang$thousandsSep <- ","
options(highcharter.lang = hcoptslang)

highchart() %>%
  hc_chart(type = "line") %>%
  hc_title(text = "Snowfall") %>%
  hc_xAxis(categories = snow$Winter) %>%
  hc_add_series(data = snow$Boston * 10, name = "Boston") %>%
  hc_yAxis(labels = list(format = "{value:,.0f}"))

However, once I add a formatter like

hc_tooltip(formatter = JS("function () { return '<b>' + this.series.name + '</b><br /> ' + this.point.y + ' <br />' + this.x;}"))

The tooltip number no longer has the comma. I think there's something I need to do to this.point.y in the formatter, but the few things I've tried haven't worked. Does anyone know what I need to add to the formatter function to make the tooltip also display the comma for the y value? Thanks.

1

1 Answers

3
votes

You can try wrapping your this.point.y in the Highcharts.numberFormat function. You can read about it in the API link or read this source description:

/**
 * Format a number and return a string based on input settings.
 *
 * @function #numberFormat
 * @memberOf Highcharts
 * @param {Number} number - The input number to format.
 * @param {Number} decimals - The amount of decimals. A value of -1 preserves
 *        the amount in the input number.
 * @param {String} [decimalPoint] - The decimal point, defaults to the one given
 *        in the lang options.
 * @param {String} [thousandsSep] - The thousands separator, defaults to the one
 *        given in the lang options.
 * @returns {String} The formatted number.
 */
H.numberFormat = function(number, decimals, decimalPoint, thousandsSep) {
    // ...
}

In my attempt I'd include the two first parameters, using -1 to preserve number of decimals. That means you should be fine with this formatter:

hc_tooltip(formatter = JS("function () { return '<b>' + this.series.name + '</b><br /> ' + Highcharts.numberFormat(this.point.y, -1) + ' <br />' + this.x;}"))