Search code examples
rhighchartsr-highcharter

How to apply color stops in highcharter?


I am trying to apply this highchart demo into R: https://jsfiddle.net/gh/get/library/pure/highcharts/highcharts/tree/master/samples/highcharts/demo/line-time-series

I got most of it to work, my issue is I am not sure how to apply the color argument for the fill gradient.

Here's my code:

library(quantmod)
library(highcharter)

df = getSymbols("SPY", from = "2021-05-01", auto.assign = F)

highchart() %>%
  hc_chart(
    type = "container", zoomType = "x") %>%
  hc_plotOptions(
    area = list(
      fillColor = list(
        linearGradient = list(
          x1 = 0,
          y1 = 0,
          x2 = 0,
          y2 = 0
        )
      )
    ),
    marker = list(
      radius = 2
    ),
    lineWidth = 1,
    states = list(
      hover = list(
        lineWidth = 1
      )
    ),
    threshold = NULL
  ) %>%
  hc_add_series(type = "area", name = "test", data = df$SPY.Close) %>%
  hc_legend(enabled = FALSE) %>%
  hc_xAxis(type = "datetime") 

Here's what my chart looks like: enter image description here

Any help is appreciated!


Solution

  • Making use of the color_stops helper you could set the stops for the fill color gradient like so:

    Note: To get a gradient you have to set y2=1 in linearGradient.

    library(quantmod)
    library(highcharter)
    
    df = getSymbols("SPY", auto.assign = F)
    
    highchart() %>%
      hc_chart(
        type = "container", zoomType = "x") %>%
      hc_plotOptions(
        area = list(
          fillColor = list(
            linearGradient = list(
              x1 = 0,
              y1 = 0,
              x2 = 0,
              y2 = 1
            ),
            stops = color_stops(n = 2, colors = c("#2f7ed8","white"))
          ),
          marker = list(
            radius = 2
          ),
          lineWidth = 1,
          states = list(
            hover = list(
              lineWidth = 1
            )
          ),
          threshold = NULL
        )
      ) %>%
      hc_add_series(type = "area", name = "test", data = df$SPY.Close) %>%
      hc_legend(enabled = FALSE) %>%
      hc_xAxis(type = "datetime")
    

    enter image description here