Search code examples
rplotr-highcharter

Add reference line for each bar in bar chart using highcharter


I want to put a specific line for each bar likes the following:

enter image description here

But, I can't. To do this, I have tried the following code to put a particular text at least, but it does not work anymore:

mydata <- data.frame(A=runif(1:10),
                   B=runif(1:10),
                   C=runif(1:10))

highchart() %>% 
hc_chart(type = "column", inverted = TRUE) %>% 
hc_title(text = "MyGraph") %>% 
hc_yAxis(title = list(text = "Weights")) %>% 
hc_plotOptions(column = list(
  dataLabels = list(enabled = FALSE),
  stacking = "normal",
  enableMouseTracking = FALSE)
) %>% 
hc_legend(layout="vertical") %>%
hc_tooltip(formatter = function(){ return("<b> test</b><br/>")},
           useHtml = TRUE) %>%
hc_series(list(name="A",data=mydata$A),
          list(name="B",data=mydata$B),
          list(name="C",data=mydata$C))

My question is how can I add red lines into the bar chart for each bar line?


Solution

  • Here is a possible solution:

    set.seed(1)
    mydata <- data.frame(A=runif(1:10), B=runif(1:10), C=runif(1:10))
    
    library(highcharter)
    hc <- highchart() %>% 
    hc_chart(type = "column", inverted = TRUE) %>% 
    hc_title(text = "MyGraph") %>% 
    hc_yAxis(title = list(text = "Weights")) %>% 
    hc_plotOptions(column = list(
      dataLabels = list(enabled = FALSE),
      stacking = "normal", groupPadding=0, 
      enableMouseTracking = FALSE)
    ) %>% 
    hc_legend(layout="vertical") %>%
    hc_tooltip(formatter = function(){ return("<b> test</b><br/>")},
               useHtml = TRUE) %>%
    hc_series(list(name="A",data=mydata$A), 
              list(name="B",data=mydata$B),
              list(name="C",data=mydata$C)) 
    
    # x position of red lines
    linepos <- c(1.3, 0.7, 1.8, 1.2, 1.0, 1.6, 0.7, 1.7, 0.8, 1.1)
    # height of red lines
    lw <- 0.35
    for (k in 1:length(linepos)) {
       df <- data.frame(x=c(k-1-lw,k-1+lw),y=rep(linepos[k],2))
       hc <- hc %>%
          hc_add_series(data = df, type = 'line', marker=list(enabled=FALSE),
              x = ~x, y= ~y, color='red', lineWidth=5, showInLegend=FALSE,
              enableMouseTracking = FALSE)
    }
    hc
    

    enter image description here