DPatrick
DPatrick

Reputation: 431

How to add a dash vertical line in r plotly with time series plot

I have a time series that looks like this:

+------------+-------+------+
| Dates      | Sales | City |
+------------+-------+------+
| 2020-01-01 | 10    | A    |
+------------+-------+------+
| 2020-01-02 | 20    | A    |
+------------+-------+------+
| 2020-01-03 | 30    | A    |
+------------+-------+------+
| 2020-01-04 | 40    | A    |
+------------+-------+------+
| 2020-01-05 | 50    | A    |
+------------+-------+------+
| 2020-01-01 | 60    | B    |
+------------+-------+------+
| 2020-01-02 | 70    | B    |
+------------+-------+------+
| 2020-01-03 | 50    | B    |
+------------+-------+------+
| 2020-01-04 | 30    | B    |
+------------+-------+------+
| 2020-01-05 | 60    | B    |
+------------+-------+------+

I would like to plot these two time series together using plotly, with different colors for different cities. Then add a vertical, dashed line at date 2020-01-03 (ofc this is just a simple pseudo dataset)

It would look something like this: enter image description here

I stopped at here:

plotly(x = ~df$Dates) %>%
 add_lines( y = ~df$Sales, color = ~df$City)

How do I add this dashed vertical line that is anchored to a specific date?

P.S. This is not a replicate question - there are a few similar questions on SO using base R or ggplot, but none close enough to solve this particular issue in Plotly using R.

Much appreciation for your help!

Upvotes: 0

Views: 1532

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 388797

One way using add_segments :

library(plotly)

plot_ly(df, x = ~Dates, y = ~Sales, type = 'scatter', mode = 'lines', color = ~City) %>%
  add_segments(y = 0, yend = 70, x = as.Date('2020-01-03'), xend = as.Date('2020-01-03'), 
               line = list(dash = "dash"), showlegend=FALSE)

enter image description here

Upvotes: 1

Related Questions