Python Forum
Add multiple vertical rectangles to a chart in plotly?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Add multiple vertical rectangles to a chart in plotly?
#3
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()
Reply


Messages In This Thread
RE: Add multiple vertical rectangles to a chart in plotly? - by snippsat - Jun-20-2023, 07:55 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  How to create a plot with line graphs and vertical bars devansing 6 2,495 Feb-28-2023, 05:38 PM
Last Post: devansing
  How to draw rectangles in pyplot? SuchtyTV 4 6,623 Jul-14-2019, 02:41 PM
Last Post: SuchtyTV
  Different templates for different rectangles python Akhou 0 2,010 May-03-2018, 01:57 PM
Last Post: Akhou
  Plotly Error muhsin 0 4,379 Mar-04-2018, 06:36 PM
Last Post: muhsin
  Vertical columns Text file Pyhton Joker92 1 3,035 Jun-02-2017, 06:17 PM
Last Post: nilamo

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020