Search code examples
javascriptrhighchartsr-highcharter

Highcharter annotation on date x-axis not working - R


I am trying to add annotation for my highcharter chart, not sure why it is not working, instead it is showing [object][object].

Here is my data,

structure(list(variable = structure(c(15522, 15553, 15584, 15614, 
15645, 15675, 15706, 15737, 15765, 15796), class = "Date"), value = c(417376, 
423563, 430290, 455643, 451542, 422419, 429472, 451694, 454900, 
456844)), row.names = c(NA, 10L), .Names = c("variable", "value"
), class = "data.frame")

Code, I am trying to add annotation only for last value in the graph, may be in a rectangle box.

currmonth <- max(pricedata$variable)
pricedata$value <- round(pricedata$value)
highchart(type = "chart") %>% 
  hc_chart(backgroundColor = "white",zoomType = 'x') %>%
  hc_add_series_times_values(pricedata$variable, pricedata$value, name = "Price") %>%
  hc_annotations(list(xValue = currmonth, title = list(text = 'Annotated chart!')))

Here is the chart,

enter image description here

You can see the annotation is in the top left corner as [object][object].

EDIT :Tried the answer and it didn't work.

enter image description here

enter image description here

enter image description here


Solution

  • Following the example https://www.highcharts.com/demo/annotations, and reading this greate tutorial https://dantonnoriega.github.io/ultinomics.org/post/2017-04-05-highcharter-explainer.html it's possible.

    First of all, it's better to create the chart using the hchart function.

    library(tidyverse) # for pull and last
    library(highcharter)
    
    currmonth <- max(data$variable)
    lastvalue <- data %>% pull(value) %>% last()
    
    hc <- hchart(data, "line", hcaes(variable, value)) 
    

    Then add the annotation replicating the given links:

    hc %>% 
      hc_annotations(
          list(
              labelOptions = list(y = 50, x = 0),
              labels = list(
                list(
                  point = list(
                    x = highcharter::datetime_to_timestamp(currmonth),
                    y = lastvalue,
                    xAxis = 0,
                    yAxis = 0
                  ),
                  text = scales::dollar(lastvalue)
                  )
                )
              )
          )
    

    enter image description here

    Sadly highchartsJS need a lot of nested lists so that is what we need to do to add annotations in highcharter (by now)