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

3

我正在使用 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个回答

3
您可以尝试使用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;}"))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接