R Highcharter Errorbar系列位置闪避

问题描述

我无法设法使误差线正确地覆盖在分组的列图中。在ggplot中,我将使用position = position_dodge(),但是在高图的错误栏文档中找不到类似的东西。

see screenshot of what I have now

这是MWE:

df <- data.frame(Gender = c("Male","Male","Female","Female"),ShareType = rep(c("Long","Short"),2),InvestedPerAccount = c(10,9,7,8),lower = c(8,6,7),upper = c(11.5,10,8.8))



highchart() %>%
  hc_add_series(df,"column",hcaes(x = ShareType,y = InvestedPerAccount,group = Gender),tooltip = list(enabled = TRUE,pointFormat = '${point.y}')) %>%
  hc_add_series(df,'errorbar',low = lower,high = upper,group = Gender,grouping = FALSE)) %>%
  hc_xAxis(categories = df$ShareType,title = list(text = "Share Type")) %>% 
  hc_colors(c("pink","lightblue"))

解决方法

我不认为这是工作的方式,但是直到找到 the 函数,这也许是一种解决方法。

highchart() %>%
  hc_add_series(df,"column",hcaes(x = ShareType,y = InvestedPerAccount,group = Gender),tooltip = list(enabled = TRUE,pointFormat = '${point.y}')) %>%
  hc_add_series(df,"errorbar",stemWidth = 1,whiskerLength = 10,grouping = FALSE,centerInCategory = TRUE,groupPadding = .68,low = lower,high = upper,group = Gender)) %>%
  hc_xAxis(categories = df$ShareType,title = list(text = "Share Type")) %>% 
  hc_colors(c("pink","lightblue"))

,

@tamtam的答案有效,但是您需要将groupPadding设置为一个奇怪的恒定值,在本例中为0.68。

真正的答案很简单-默认情况下,错误栏系列已连接到先前的系列。因此,应按以下方式定义系列的顺序:

1. column 2. errorbar 3. column 4. errorbar

显示正确顺序的演示:https://jsfiddle.net/BlackLabel/rmhw6f9y/

但是R包装器按以下顺序添加它们:

1. column 2. column 3. errorbar 4. errorbar

演示显示了错误的顺序:https://jsfiddle.net/BlackLabel/bw0p68f3/


由于4.错误栏未连接到列(3.不是列系列),因此错误栏的分组不正确。

解决方案很简单-您需要将3.与1.和4.与2.连接。为此,您可以使用 column.id 和 errorbar.linkedTo 属性:

https://api.highcharts.com/highcharts/series.column.id https://api.highcharts.com/highcharts/series.errorbar.linkedTo

我不知道如何将它们添加到图表选项(hc_add_series)中,但是我知道如何使用JavaScript更新系列:

hc_chart(events = list(load = JS("function () {
    this.series[0].update({
      id: 'firstColumnSeries'
    },false);
    this.series[1].update({
      id: 'secondColumnSeries'
    },false);
    this.series[2].update({
      linkedTo: 'secondColumnSeries'
    },false);
    this.series[3].update({
      linkedTo: 'firstColumnSeries'
    });
  }"))) %>%

这是完整的代码:

library('highcharter')

df <- data.frame(Gender = c("Male","Male","Female","Female"),ShareType = rep(c("Long","Short"),2),InvestedPerAccount = c(10,9,7,8),lower = c(8,6,7),upper = c(11.5,10,8.8))


highchart() %>%
  hc_chart(events = list(load = JS("function () {
    this.series[0].update({
      id: 'firstColumnSeries'
    },false);
    this.series[3].update({
      linkedTo: 'firstColumnSeries'
    });
  }"))) %>%
  hc_add_series(df,'errorbar',group = Gender,grouping = FALSE)) %>%
  hc_xAxis(categories = df$ShareType,"lightblue"))

ps。您可能希望将secondColumnSeriesfirstColumnSeries交换,具体取决于您要放置错误栏的那一侧。