Search code examples
rhighchartsr-highcharter

Manually reordering Bar Chart in R Highchart


I'm kind of new to highcharter and I'm trying to manually reorder the categories of a bar chart but I can't seem to find an immediate solution. I tried to reorder with fct_relevel but it doesn't work

My code looks something like this:

library(highcharter)
library(tidyverse)

df <- data.frame(x= rep(c("john", "Luke", "Tom", "Sarah", "Laura", "Stacy"), each = 2), 
                 y = round(runif(12, min=0, max=100)),
                 z = rep(c(2020, 2021), each = 6)
                 )

df %>% hchart("bar", hcaes(x = x, y = y, group = z))

enter image description here

Basically, I'd like to be able to manually set the order of the axis categories and reposition them as I prefer, for example by placing Luke last and Stacy first.

Does anyone have a solution to this?


Solution

  • An easy way is to use hc_axis to define the order of the categories.

    library(highcharter)
    library(tidyverse)
    
    df %>%
      hchart("bar", hcaes(x = x, y = y, group = z)) %>%
      hc_xAxis(categories = list("Stacy", "john", "Tom", "Sarah", "Laura", "Luke"))
    

    Output enter image description here

    Data

    set.seed(123)
    
    df <-
      data.frame(x = rep(c(
        "john", "Luke", "Tom", "Sarah", "Laura", "Stacy"
      ), each = 2),
      y = round(runif(12, min = 0, max = 100)),
      z = rep(c(2020, 2021), 6))