Search code examples
rhighchartsboxplotr-highcharter

Is there a way to color boxplots based on group in hcboxplot()?


I am trying to make boxplots using highcharter in R that all have distinct colors based on their group. I cannot figure out how to make all the boxes have distinct colors. What should I do to resolve this?

library(highcharter)
library(viridisLite)
library(dplyr)
hcboxplot(x = mpg$cty, var = mpg$manufacturer, outliers = FALSE) %>%
  hc_chart(type = "column") %>%
  hc_colors(viridis(15))

Solution

  • Since, at least for me, the link in the comments did not lead me directly to a solution, I want to provide my approach below:

    library(highcharter)
    library(viridisLite)
    library(magrittr)
    library(ggplot2) # just for the mpg data
    
    hcboxplot(x = mpg$cty, var = mpg$manufacturer, outliers = FALSE) %>% 
      hc_plotOptions(boxplot = list(
        # it's only possible to provide one single color. This, we want to replace in JS.
        fillColor = "red")) %>% 
      hc_chart(type = "column", 
               events = list(
                 load = JS('function() {
                  var chart = this;
    
                  // dput(viridis(15)) and make it available as a list in JS
                  var colors = ["#440154FF", "#481B6DFF", "#46337EFF", "#3F4889FF", "#365C8DFF", 
                           "#2E6E8EFF", "#277F8EFF", "#21908CFF", "#1FA187FF", "#2DB27DFF", 
                           "#4AC16DFF", "#71CF57FF", "#9FDA3AFF", "#CFE11CFF", "#FDE725FF"];
    
                  // iterate over all data elements (boxplots) and change the desired property
                  for (var i=0; i< chart.series[0].data.length; i++){
                  chart.series[0].data[i].box.element.attributes.fill.value = colors[i]
                  }
                  }')
               ))