2

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))
Altamash Rafiq
  • 349
  • 1
  • 2
  • 10
  • 2
    Have a look at the links [here](https://stackoverflow.com/questions/55134120/customize-colors-for-boxplot-with-highcharter) to see how you could style `highcharter` boxplots. – Sven Jun 20 '19 at 08:14
  • Please give feedback about answers so the community knows whether the problem is solved or not – mnist Oct 27 '19 at 08:18
  • @`Altamash Rafiq` that was an excellent question! – yeahman269 Aug 24 '20 at 14:07

2 Answers2

2

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]
              }
              }')
           )) 
halfer
  • 19,824
  • 17
  • 99
  • 186
mnist
  • 6,571
  • 1
  • 18
  • 41
1

It works by setting hc_plotOptions(series=list(colorByPoint=TRUE)):

library(viridisLite)
library(dplyr)
library(ggplot2) 

hcboxplot(x = mpg$cty, var = mpg$manufacturer, outliers = FALSE) %>%
  hc_chart(type = "column") %>%
  hc_colors(viridis(15)) %>% 
  hc_plotOptions(series=list(colorByPoint=TRUE))

enter image description here

RLave
  • 8,144
  • 3
  • 21
  • 37