Python Forum

Full Version: Add multiple vertical rectangles to a chart in plotly?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I'm struggling to figure out how to create multiple vertical rectangles that span entire plots using plotly.

I'm assuming this is possible using add_vrect()?

Below is the code that I want to add the vertical rectangles to – with the hope of spanning all of the dates corresponding with the "Recession" periods found in the attached data set.

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 DJI 
fig = go.Figure()
fig.add_trace(go.Scatter(x=history.index, y=history["DJI"], mode="lines"))

# Show plot
fig.show()
Not sure what a "vertical" rectangle is.

This link shows how to draw a rectangle using data coordinates.

https://stackoverflow.com/questions/1301...tlib-graph

This link talks about adding vertical bars to a plot.

https://python-forum.io/thread-39474.html
I guess something like this is whant you want.
import pandas as pd
import plotly.graph_objects as go

history = pd.read_csv("sample_data.csv")
history["Date"] = pd.to_datetime(history["Date"], format="%Y-%m-%d")
history.set_index("Date", inplace=True)
recession_dates = history.loc[history["Regime"] == "Recession"].index
normal_dates = history.loc[history["Regime"] == "Normal"].index
fig = go.Figure()
fig.add_trace(go.Scatter(x=history.index, y=history["DJI"], mode="lines"))

# Add vertical rectangles for recession periods
for start_date, end_date in zip(recession_dates[:-1], recession_dates[1:]):
    fig.add_vrect(
        x0=start_date,
        x1=end_date,
        fillcolor="red",
        opacity=0.2,
        layer="below",
        line_width=0,
    )

# Add vertical rectangles for normal periods
for start_date, end_date in zip(normal_dates[:-1], normal_dates[1:]):
    fig.add_vrect(
        x0=start_date,
        x1=end_date,
        fillcolor="green",
        opacity=0.2,
        layer="below",
        line_width=0,
    )

# Adjust plot size
fig.update_layout(
    autosize=False,
    width=1400,
    height=800,
)

fig.show()