将逗号格式添加到Highcharter工具提示

时间:2017-03-19 01:45:43

标签: r highcharts

使用Joshua Kunt的Highcharter R package,我正在尝试添加自定义工具提示格式编号,以便成千上万的逗号分隔符。如果我不自定义工具提示,当我使用以下代码时,Y轴和工具提示格式正确:

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}"))

但是,一旦我添加了像

这样的格式化程序
hc_tooltip(formatter = JS("function () { return '<b>' + this.series.name + '</b><br /> ' + this.point.y + ' <br />' + this.x;}"))

工具提示编号不再包含逗号。我认为我需要在格式化程序中对this.point.y做一些事情,但我尝试过的一些事情并没有奏效。有谁知道我需要添加到格式化程序函数,以使工具提示也显示y值的逗号?感谢。

1 个答案:

答案 0 :(得分:1)

您可以尝试在Highcharts.numberFormat功能中包装this.point.y。您可以在API链接中阅读它或阅读此源描述:

/**
 * 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) {
    // ...
}

在我的尝试中,我包括两个第一个参数,使用-1来保留小数位数。这意味着你应该对这个格式化程序没问题:

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