Reputation: 149
I would like to draw a rectangle polygon over a plotly plot that uses dates. As a toy example my code is
library(tidyverse)
library(plotly)
df <- tibble(daydate = dmy(c("01-01-2022", "01-02-2022", "15-02-2022", "27-02-2022")),
value = runif(4, 0, 100))
plot_ly(df, x = ~daydate, y = ~value, color = I("#9B4393"), type = 'scatter', mode = 'lines')
I would like to draw a rectangle that spans the dates "01-02-2022" to "15-02-2022", and from 0 to 100. Also, I would like to have the rectangular area grey colour that is quite transparent.
Many thanks
Upvotes: 1
Views: 1138
Reputation: 20454
Define a rectangle:
my_rectangle <- list(
type = "rect",
fillcolor = "grey",
line = list(color = "black"),
opacity = 0.3,
x0 = "2022-02-01",
x1 = "2022-02-15",
xref = "x",
y0 = 0,
y1 = 100,
yref = "y"
)
Add it to the plot:
plot_ly(
df,
x = ~daydate,
y = ~value,
color = I("#9B4393"),
type = "scatter",
mode = "lines"
) |>
layout(
shapes = list(
my_rectangle
)
)
The R plotly documentation sets out how you can draw and style rectangles and various other shapes.
Upvotes: 1