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

标签 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 值的逗号?谢谢。

最佳答案

您可以尝试将您的 this.point.y 包装在 Highcharts.numberFormat 中功能。您可以在 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;}"))

关于r - 将逗号格式添加到 Highcharter 工具提示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42882018/

相关文章:

javascript - 将 Highcharts(和模块)与 lit-element 一起使用

javascript - 如何从其他脚本中获取值(value)? (在 html 中)

javascript - Highcharts - 实时更新柱形图

R - 识别数据框列中的常见元素

r - 在ggplot中绘制混合效果模型

r - 在小插图中为包本身加载 R 包

javascript - Highcharts 颜色不显示

c++ - 如何通过 Rcpp 在 R 中使用 C++ 函数模板?

r - 检测被 NaN/NA 模式包围的单个值

javascript - Highcharts 工具提示对于被黑的甘特图无法正常工作