highchartsr-highcharter

Set conditional color and pattern for highcharter column chart


I would like to create a column chart where only the last column has a pattern (for year 2020 in the example below) and the rest of the columns have a solid fill. I know about the pattern fill module which can be added with hc_add_dependency("modules/pattern-fill.js") but I'm struggling to make it work for my chart. In fact, I can't even change the default (solid) colors to custom colors. I would really appreciate your help! Thanks so much!

Here is a minimal example:

library(tidyverse)
library(highcharter)

df <- data.frame(cbind(seq(2001, 2020, by=1),
                       sample(1:15, size=20, replace=T),
                       sample(1:15, size=20, replace=T))) 
colnames(df) <- c("year", "newA", "newB")

  highchart() %>%
    hc_chart(type = "column") %>%
    hc_add_series(
      name = "New A",
      data = df$newA,
      stack = "new",
      showInLegend = F) %>%
    hc_add_series(
      name = "New B",
      data = df$newB,
      stack = "new",
      showInLegend = F) %>%
    hc_plotOptions(column = list(stacking = "normal")) %>%
    hc_xAxis(categories = df$year, title = list(text = ""))

Solution

  • In this example, a column chart is created with a single series of data. Only the last column (for 'Day 3') is filled with a pattern, as specified in the hc_add_series() function. For this column, instead of providing just a value, we provide a list containing the value ('y') and the color specification:

    library(highcharter)
    
    Column_with_stripe <- highchart() %>%
      hc_chart(type = "column") %>%
      hc_add_dependency("modules/pattern-fill.js") %>%
      hc_xAxis(categories = c('Day 1', 'Day 2', 'Day 3'), tickmarkPlacement = "on") %>%
      hc_yAxis(title = list(text = "Value")) %>%
      hc_plotOptions(line = list (datalabels = list(enabled = TRUE), enableMouseTracking = FALSE)) %>%
      hc_add_series(
        name = "Var1", 
        data = list(
          5, # Day 1
          8, # Day 2
          list(y = 10, color = list(pattern = list(path = 'M 0 0 L 10 10 M 9 -1 L 11 1 M -1 9 L 1 11', width = 5, height = 5, color = '#f00'))) # Day 3
        ),
        color = "black"
      )
    
    print(Column_with_stripe)