Search code examples
rr-highcharter

Why there are no intended labels on this highcharter plot - R


I have the following data frame:

library(dplyr)
library(highcharter)
hc <- structure(list(date_ref = c("2020-03-02", "2021-02-02", "2021-03-02"
), bracket_pay = c("T1", "T1", "T1"), col1 = c(10010, 12010, 11090), col2 = c(9850, 
11300, 10080), ratio = c(98.40, 94.09, 90.89)), row.names = c(NA, -3L), class = c("tbl_df", "tbl", 
"data.frame"))

The data is:

# A tibble: 3 x 5
  date_ref   bracket_pay    col1    col2 ratio
  <chr>      <chr>         <dbl>   <dbl> <dbl>
1 2020-03-02 T1           10010.   9850.  98.4
2 2021-02-02 T1           12010.  11300.  94.1
3 2021-03-02 T1           11090.  10080.  90.9

I want to create a combined plot (column and line) using highcharter. This is what I tried:

highchart() %>% 
  hc_yAxis_multiples(
    list(title = list(text = "Amount"),
         opposite = FALSE),
    list(title = list(text = "Percentage"),
         opposite = TRUE)) %>% 
  hc_add_series(hc, hcaes(x = date_ref, y = col2),
                yAxis = 0,
                name = "Amount",
                type = "column",
                color = "mediumseagreen") %>%
  hc_add_series(hc, hcaes(x = date_ref, y = ratio),
                yAxis = 1,
                name = "Advanced",
                type = "line",
                color = "tomato")

And the plot is almost good, however when you see the labels on the X axis, you see 1,2,3 instead of 2020-03-02,2021-02-02,2021-03-03. By the way date_ref is a character vector. Please, any help will be greatly appreciated.


Solution

  • Adding hc_xAxis(type = 'category') seems to fix it.

    highchart() %>% 
    hc_xAxis(type = 'category') %>%
    hc_yAxis_multiples(
        list(title = list(text = "Amount"),
             opposite = FALSE),
        list(title = list(text = "Percentage"),
             opposite = TRUE)) %>% 
    hc_add_series(hc, hcaes(x = date_ref, y = col2),
                  yAxis = 0,
                  name = "Amount",
                  type = "column",
                  color = "mediumseagreen") %>%
    hc_add_series(hc, hcaes(x = date_ref, y = ratio),
                  yAxis = 1,
                  name = "Advanced",
                  type = "line",
                  color = "tomato")