Search code examples
rdateplotlyline

R plot_ly() adding vertical lines to time data


I would like to add a vertical line on a special date to my plot. I am using the plot_ly() function from the plotly package in R.

 p <- plot_ly(dt.allDataFvsS, x = dt.allDataFvsS$date, y = dt.allDataFvsS$meanDifference, mode = 'lines',
              type = "scatter", line = list(color = " #007d3c")) %>%
      layout(title = "Average Price Difference Forward vs. Spot", xaxis = list(title = "Date"),
             yaxis = list(title = "EUR / MWh"))
 

     

The date has the following form: e.g. "2018-10-01" ("Y-M-D")

My plot looks like this:

PLOT

So, my question is how do I get a black vertical line at date "2018-10-01" ? Is it also possible to have vertical lines at the beginning of each year? Or of every quarter (Jan - Apr - Jul - Oct) of each year?

I would be very happy if someone could help me? Unfortunately, after a day of browsing the internet, I couldn't find anything that worked.


Solution

  • As no data is provided to reproduce your issue, I would suggest next approach using add_trace() function where you define the coordinates for the line:

    p <- plot_ly(dt.allDataFvsS, x = dt.allDataFvsS$date, y = dt.allDataFvsS$meanDifference, mode = 'lines',
                 type = "scatter", line = list(color = " #007d3c")) %>%
      add_trace(x =as.Date("2018-10-01"),type = 'scatter', mode = 'lines',
                line = list(color = 'black'),name = '') %>%
      layout(title = "Average Price Difference Forward vs. Spot", xaxis = list(title = "Date"),
             yaxis = list(title = "EUR / MWh"))
    

    Let me know if that works!