Search code examples
rr-highcharter

Change the size of the second section of Highchart in R


Trying to use R highchart with customized section heights as that will highlight the relative price at different times. The second section displaying the volume is taking more space and is more figurative in nature inform. Can we assign the relative height to different sections similar to what we provide for device width. The code provided by @Dominik.Chudy in Colors for volume indicators

library(highcharter)

data <- data.frame(
  Date = as.Date('2023-01-01') + 0:4,
  Open = c(100, 105, 102, 108, 110),
  High = c(110, 107, 108, 112, 115),
  Low = c(95, 100, 99, 105, 107),
  Close = c(105, 102, 108, 100, 113),
  Volume = c(1000, 1500, 1200, 1300, 1600)
)

hc_data <- lapply(1:nrow(data), function(i) {
  list(
    as.numeric(as.POSIXct(data$Date[i])) * 1000,
    data$Open[i],
    data$High[i],
    data$Low[i],
    data$Close[i]
  )
})

hc_volume <- lapply(1:nrow(data), function(i) {
  list(
    x = as.numeric(as.POSIXct(data$Date[i])) * 1000,
    y = data$Volume[i],
    color = ifelse(data$Close[i] > data$Open[i], 'green', 'red')    
  )
})

hchart <- highchart(type = "stock") %>%
  hc_title(text = "Candlestick and Volume Chart") %>%
  hc_yAxis_multiples(
    list(title = list(text = "OHLC"), height = "60%", lineWidth = 2),
    list(title = list(text = "Volume"), top = "65%", height = "35%", offset = 0, lineWidth = 2)
  ) %>%
  hc_add_series(type = "candlestick", name = "AAPL", data = hc_data) %>%
  hc_add_series(type = "column", name = "Volume", data = hc_volume, yAxis = 1)%>%
  hc_plotOptions(candlestick = list(color = 'red', upColor = 'green', lineColor = 'red', upLineColor = 'green'))  
print(hchart)

Solution

  • You could separately define two y-axes and set their relative heights (see ?hc_yAxis_multiples, bottom example):

    
        highchart(type = "stock") %>%
          hc_title(text = "Candlestick and Volume Chart") %>%
          hc_add_series(type = "candlestick", name = "AAPL", data = hc_data,
                        yAxis = 0 ## remember to assign to one of the two y-axes!
                        ) %>%
          hc_add_yAxis(title = list(text = "OHLC"), lineWidth = 2,
                       relative = 65
          )  %>%
          hc_add_series(type = "column", name = "Volume", data = hc_volume,
                        yAxis = 1 
                        ) %>%
          hc_add_yAxis(title = list(text = "Volume"), offset = 0, lineWidth = 2,
                       relative = 35
                       ) %>% 
          hc_plotOptions(candlestick = list(color = 'red', upColor = 'green', lineColor = 'red', upLineColor = 'green')) %>% 
          print()
    
    

    highchart with different panel heights