Search code examples
rhighchartsshinyr-highcharter

R Highcharter: Polar graph having conditional colors


I am using Highcharter's Polar graphs and was wondering if it has the ability to change colors based on criteria. I am using the graph to look at budget versus spend. When spend < budget, I would like the column to be green. When spend > budget, I would like the column to be red. Is this possible?

For the example in the code: 'Logistics' and 'IT & Telecom' spend would be green, all other spend categories would be red.

The answer needs to be dynamic as what is over or under plan will be changing constantly.

Below is a simplified version of the code.

library (shiny)
library (highcharter)

hc <- highchart() %>% 
  hc_chart(polar = TRUE) %>% 
  hc_title(text = "Budget vs Spending") %>% 
  hc_xAxis(categories = c("Energy", "Facilties", "IT & Telecom",
                          "Logistics", "Office Products", "Plant Consumables",
                          "Temp Labor", "Travel", "Other"),
           tickmarkPlacement = "on",
           lineWidth = 0) %>% 
  hc_yAxis(gridLineInterpolation = "polygon",
           lineWidth = 0,
           min = 0) %>% 
  hc_series(
    list(
      name = "Spend",
      data = c(50000, 39000, 42000, 31000, 26000, 14000, 26000, 26000, 26000),
      pointPlacement = "on",
      type = "column"
    ),
    list(
      name = "Budget",
      data = c(43000, 19000, 60000, 35000, 17000, 10000,10000,10000,10000),
      pointPlacement = "on",
      type = "line"
    )
  )

hc

Solution

  • You want to set colorByPoint to TRUE and then use an ifelse to set the colors, like this:

    library(shiny)
    library(highcharter)
    library(tidyverse)
    hc <- highchart() %>% 
      hc_chart(polar = TRUE) %>% 
      hc_title(text = "Budget vs Spending") %>% 
      hc_xAxis(categories = c("Energy", "Facilties", "IT & Telecom",
                              "Logistics", "Office Products", "Plant Consumables",
                              "Temp Labor", "Travel", "Other"),
               tickmarkPlacement = "on",
               lineWidth = 0) %>% 
      hc_yAxis(gridLineInterpolation = "polygon",
               lineWidth = 0,
               min = 0) %>% 
      hc_series(
        list(
          name = "Spend",
          data = c(50000, 39000, 42000, 31000, 26000, 14000, 26000, 26000, 26000),
          pointPlacement = "on",
          colorByPoint = TRUE,
          type = "column",
          colors = ifelse(c(50000, 39000, 42000, 31000, 26000, 14000, 26000, 26000, 26000) > c(43000, 19000, 60000, 35000, 17000, 10000,10000,10000,10000),"#F00","#0F0")
        ),
        list(
          name = "Budget",
          data = c(43000, 19000, 60000, 35000, 17000, 10000,10000,10000,10000),
          pointPlacement = "on",
          type = "line"
        )
      )
    
    hc
    

    hope this helps