Search code examples
rhighchartsrcharts

Custom legend in rCharts (highcharts)


I have a dataframe that looks like:

## Data
df <- data.frame(label = c("A", "B", "C", "D"), 
                 color = c("red", "red", "blue", "green"), 
                 y = c(10, 11, 12, 13))

"A" and "B" are part of the same category, while "C" and "D" are part of separate categories.

I would like to add a legend on the chart with category labels.

## Highchart without Legend

## Basic highchart
h <- rCharts:::Highcharts$new()
h$chart(type = "column")

## Highchart data:
h$series(showInLegend = FALSE, data =  rCharts::toJSONArray2(df[, c("label", "color", "y")], json = FALSE, names = TRUE))

## Highchart options:
h$xAxis(categories = unique(df$label), labels = list(rotation = 0, align = 'center', style = list(fontSize = '12px', fontFamily = 'Verdana, sans-serif')), replace = FALSE)
h$tooltip(formatter = "#! function() {return this.x + ': ' + this.y; } !#")
h$plotOptions(series = list(color = df$color), column = list(grouping = FALSE))
h  # display highchart

enter image description here

I haven't found a method that makes any sense to solve this problem.

Any help would be appreciated.


Solution

  • And here's how I solved it.

    Each 'category' is split into a separate series with an x value to determine its location on the graph (highcharts requires this for some reason. Without it, the graphs stack).

    Here's a sample code that works:

    ## Highchart with Legend
    ## Remark: simply switching showInLegend to TRUE will not work
    df$x <- c(0, 1, 2, 3) # add an index to dataframe (starting from 0)
                          # and pass it to h$series data
    h <- rCharts:::Highcharts$new()
    h$chart(type = "column")
    h$series(name = "Category 1 (Red)", color = "red", data = rCharts::toJSONArray2(df[df$color == "red", c("label", "color", "x", "y")], json = FALSE, names = TRUE))
    h$series(name = "Category 2 (Blue)", color = "blue", data = rCharts::toJSONArray2(df[df$color == "blue", c("label", "color", "x", "y")], json = FALSE, names = TRUE))
    h$series(name = "Category 3 (Green)", color = "green", data =  rCharts::toJSONArray2(df[df$color == "green", c("label", "color", "x", "y")], json = FALSE, names = TRUE)) 
    h$xAxis(categories = unique(df$label), labels = list(rotation = 0, align = 'center', style = list(fontSize = '12px', fontFamily = 'Verdana, sans-serif')), replace = FALSE)
    h$tooltip(formatter = "#! function() {return this.x + ': ' + this.y; } !#")
    h$plotOptions(series = list(color = df$color), column = list(grouping = FALSE))
    h # display chart
    

    enter image description here

    I hope this helps someone else.