I'm struggling to figure out how to create multiple rectangles that span entire plots using plotly.
I've done this with matplotlib using axvspan():
for month in recession:
plt.axvspan(month, month + pd.offsets.MonthEnd(0), color="red", alpha=0.1)
I'm assuming this is possible using add_vrect()?
Below is the code along with a sample data set that I want to add the vertical rectangles to with the hope of spanning all of the dates corresponding with the Recession periods. Any help would be greatly appreciated.
import pandas as pd
import plotly.graph_objects as go
import datetime
# Load data
history = pd.read_csv("sample_data.csv")
history["Date"] = pd.to_datetime(history["Date"], format="%Y-%m-%d")
history.set_index("Date", inplace=True)
# Filter out recession dates
recession = history.loc[history["Regime"] == "Recession"].index
# Plot Dow Jones average against time
fig = go.Figure()
fig.add_trace(go.Scatter(x=history.index, y=history["DJI"], mode="lines"))
# Show plot
fig.show()
Sample Data
Date | Regime | DJI |
---|---|---|
1907-01-01 | Normal | 68.33 |
1907-02-01 | Normal | 66.41 |
1907-03-01 | Normal | 65.57 |
1907-04-01 | Recession | 58.05 |
1907-05-01 | Recession | 61.05 |
1907-06-01 | Recession | 56.56 |
1907-07-01 | Recession | 57.94 |
1907-08-01 | Normal | 62.35 |
1907-09-01 | Normal | 63.01 |
1907-10-01 | Normal | 63.29 |
1907-11-01 | Normal | 62.99 |
1907-12-01 | Normal | 63.17 |
1908-01-01 | Normal | 63.28 |
1908-02-01 | Normal | 63.41 |
1908-03-01 | Normal | 63.83 |
1908-04-01 | Normal | 63.11 |
1908-05-01 | Recession | 59.26 |
1908-06-01 | Recession | 58.99 |
1908-07-01 | Recession | 58.37 |
1908-08-01 | Recession | 58.01 |
1908-09-01 | Recession | 57.66 |
1908-10-01 | Recession | 57.23 |
1908-11-01 | Recession | 56.84 |
1908-12-01 | Recession | 56.76 |
1909-01-01 | Recession | 56.24 |
1909-02-01 | Recession | 57.15 |
1909-03-01 | Recession | 57.89 |
1909-04-01 | Normal | 61.01 |
1909-05-01 | Normal | 61.34 |
1909-06-01 | Normal | 61.92 |
1909-07-01 | Normal | 62.39 |
1909-08-01 | Normal | 63.01 |
1909-09-01 | Normal | 63.22 |
1909-10-01 | Normal | 63.89 |
1909-11-01 | Normal | 64.21 |
1909-12-01 | Normal | 64.88 |