Search code examples
rggplot2highchartsdata-visualizationr-highcharter

R Highcharter Errorbar Series Position Dodge


I can't manage to get the error bars to overlay properly on my grouped column plot. In ggplot I would use position = position_dodge(), but I haven't been able to find something similar in the errorbar documentation for highcharts.

see screenshot of what I have now

Here's a 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,7,6,7),
                 upper = c(11.5,10,9,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', hcaes(x = ShareType, low = lower, high = upper, group = Gender, grouping = FALSE)) %>%
  hc_xAxis(categories = df$ShareType, title = list(text = "Share Type")) %>% 
  hc_colors(c("pink","lightblue"))


Solution

  • A solution would be use id parameter in the first group of series and then use linkedTo in the errorbar series. Due the "errobar" type series is linked to the previous one by default.

    example_dat <- tibble(Type = c("Human", "High-Elf", "Orc"), 
           key = c("World1", "World2", "World3")) %>% 
      expand.grid() %>% 
      mutate(mean = runif(9, 5, 7)) %>% 
      mutate(sd = runif(9, 0, 2)) 
    
    
    hchart(
      example_dat, 
      "column",
      hcaes(x = key, y = mean, group = Type),
      id = c("a", "b", "c")
      ) %>%
      
      hc_add_series(
        example_dat,
        "errorbar", 
        hcaes(y = mean, x = key, low = mean - sd, high = mean + sd, group = Type),
        linkedTo = c("a", "b", "c"),
        enableMouseTracking = TRUE,
        showInLegend = FALSE
        ) %>% 
      
      hc_plotOptions(
        errorbar = list(
          color = "black", 
          # whiskerLength = 1,
          stemWidth = 1
        ) 
      ) 
    

    enter image description here