rggplot2highchartsrcharts

plot vline graph highcharts in r


I need to plot a vertical line on a graph, and write the texts "PRE" and "POS" as shown in the attached figure, using the package and highcharts. So far I have not been successful. Follow my code so far.

hc <- bd
  
  plotline <- list(color ="red", value =2015.5, width =5)

  hchart('line', hcaes(x = hc$ANO, y = hc$Percentual, group = Niveis)%>%
  hc_yAxis(plotLines = list(plotline)) 
   
) 

hc

Desired result


Solution

  • You didn't provide data, so I grabbed some to use. I didn't try to match styles or colors - you didn't indicate that was a need.

    library(tidyverse)
    library(highcharter)
    library(lubridate)
    
    weather # from highcharter package
    w2 = weather %>% pivot_longer(min_temperaturec:mean_temperaturec, names_to = "Niveis", values_to = "Percentual")
    
    hchart(w2, 'line', hcaes(x = date, 
                             y = Percentual, 
                             group = Niveis)) %>%  
      hc_xAxis(plotLines = list(list(value = datetime_to_timestamp(median(w2$date)),  # I used the median date
                                                                                      # any 'date' you use needs the function
                                                                                      # datetime_to_timestamp()
                                        width = 5, color = "red"))) %>% 
      # add Z index to put on top zIndex = 5
      hc_annotations(list(
        labels = 
          list(
            list(
              point = list(x = datetime_to_timestamp(min(w2$date)),       # using the minimum date
                           y = max(w2$Percentual), xAxis = 0, yAxis = 0), # using the maximum y value
              text = "PRE"
            ),
            list(
              point = list(x = datetime_to_timestamp(max(w2$date)),       # using the maximum date
                           y = max(w2$Percentual), xAxis = 0, yAxis = 0), # using the maximum y value
              text = "POST"
            ))))
    

    enter image description here