1

我正在使用 highcharter 包制作直方图。我想摆脱默认的分数范围显示 - (x, y]- 并将其替换为以下内容:score ranges: x to y

library(highcharter)
apple <- c(0, 22, 5, 32, 34, 35, 56, 67, 42, 67, 12, 99, 46, 78, 43, 67, 33, 11)
hchart(apple, color = "#a40c19", breaks = 20) %>% 
  hc_yAxis(title = list(text = "Number of Apples")) %>% 
  hc_xAxis(title = list(text = "Score (0-100)")) %>%
  hc_tooltip(borderWidth = 1, sort = TRUE, crosshairs = TRUE,
             pointFormat = "Score Range: {point.x} to {point.x} <br> Number of Apples: {point.y}") %>%
  hc_legend(enabled = FALSE)

例如,在下图中,我想去掉标题(30, 35]并将其替换为Score Range: 30 to 35. 在此处输入图像描述

4

1 回答 1

2

首先,您需要知道直方图的间隔长度是多少:

library(highcharter)
apple <- c(0, 22, 5, 32, 34, 35, 56, 67, 42, 67, 12, 99, 46, 78, 43, 67, 33, 11)

h <- hist(apple, breaks = 20)
d <- diff(h$breaks)[1]
d
> d
[1] 5

现在,您需要使用pointFormatter而不是pointFormat因为允许您对工具提示的输出进行更多控制。pointFormat需要一个字符串模板并且pointFormatter需要一个 javascript 函数。

您将 放入delta该函数以获得每个间隔的正确限制。显然你可以做得更优雅,但这就是想法。

hchart(h, color = "#a40c19", breaks = 20) %>% 
  hc_yAxis(title = list(text = "Number of Apples")) %>% 
  hc_xAxis(title = list(text = "Score (0-100)")) %>%
  hc_tooltip(borderWidth = 1, sort = TRUE, crosshairs = TRUE,
             headerFormat = "",
             pointFormatter = JS("function() {
return 'Score Range:'  + (this.x - 5/2) + ' to ' + (this.x + 5/2) + '<br> Number of Apples:' +  this.y;    
             }")) %>%
  hc_legend(enabled = FALSE)

在此处输入图像描述

最后,您使用headerFormat = ""删除标题。

于 2017-11-22T21:33:15.193 回答