Search code examples
rvisualizationr-highcharter

Color bars of highcharter histogram above/below threshold


I'd like to create an interactive version of a histogram with bars colored according to whether they are above/below a threshold value but I'm struggling to implement what is pretty straightforward in ggplot2 in highcharter. Any advice or ideas are welcome!

# load libraries
library(highcharter)
library(ggplot2)
library(dplyr)

# ggplot example ----

# set threshold values as columns
plot_data <- mtcars |>
  mutate(group = case_when(
    mpg < 20 ~ "below_threshold",
    mpg >= 20 ~ "above_threshold"
  ))

# create histogram
ggplot(plot_data, aes(x = mpg, fill = group)) +
  geom_histogram(binwidth = 5, boundary = 0) +
  scale_fill_manual(values = c(
    "below_threshold" = "lightgrey",
    "above_threshold" = "lightblue"
  )) +
  xlim(0, 40) +
  theme_minimal() +
  theme(legend.position = "none")

# highcharter example ----

# use hist to set manual breaks
data <- hist(mtcars$mpg, plot = FALSE, breaks = seq(0, 40, by = 5))

# save color vector and add to list object
cols <- c(rep("lightgrey", 4), rep("lightblue", 4))
data$color_palette <- cols

# generate histogram
hchart(data)

# assigns first color in palette to whole chart
hchart(data) |>
  hc_colors(data$color_palette)

Solution

  • I think you'll need to use colorZones for this. You can set it up as follows.

    hchart(data) %>%
      hc_plotOptions(series = list(
        zoneAxis = "x",
        zones = list(
          list(value = 20, color = 'lightgrey'), # all values <= 20, = 'lightgrey'
          list(color = 'lightblue')
        )
      ))
    

    enter image description here