I am trying to plot some weather data and add some zones (sessions) over the plots.
def create_plot(filtered_weather_df, filtered_session_df):
if filtered_weather_df.empty:
return go.Figure()
filtered_weather_df = filtered_weather_df.copy()
filtered_weather_df["PlotTime"] = pd.to_datetime(
"1970-01-01 " + filtered_weather_df["TimeOfDay"].astype(str)
)
filtered_session_df = filtered_session_df.copy()
for col in ['start', 'end']:
filtered_session_df[f"Plot{col}"] = pd.to_datetime(
"1970-01-01 " + filtered_session_df[col].dt.strftime('%H:%M:%S')
)
fig = make_subplots(rows=1, cols=2,
vertical_spacing=0.05,
horizontal_spacing=0.05,
shared_xaxes=True,
subplot_titles=("Air Temperature", "Humidity"))
color_map = {d: c for d, c in zip(sorted(filtered_weather_df["Date"].unique()), px.colors.qualitative.Light24)}
marker_styles = ["circle", "diamond", "square", "cross", "x", "triangle-up", "star"]
for _, session in filtered_session_df.iterrows():
print(session["name"], session["Plotstart"], session["Plotend"])
session_date = session["start_date"]
session_colour = color_map.get(session_date, "gray")
for column in [1, 2]:
xref = f"x{'' if column == 1 else column}"
print(f"Adding zone between {session['Plotstart']} and {session['Plotend']}")
fig.add_vrect(
x0=session["Plotstart"],
x1=session["Plotend"],
fillcolor=session_colour,
opacity=0.5, # 90% reduced opacity
layer="below",
line_width=0,
row=1,
col=column,
xref=xref
)
for x in [session["Plotstart"], session["Plotend"]]:
fig.add_vline(
x=x,
line=dict(color=session_colour, width=2),
row=1,
col=column,
xref=xref
)
middle_time = session["Plotstart"] + (session["Plotend"] - session["Plotstart"])/2
fig.add_annotation(
x=middle_time,
y=5, # Position above the plot
yref="paper",
text=session["name"],
showarrow=False,
font=dict(size=14, color='#000000'),
row=1,
col=column
)
fig.update_layout(height=800, legend_title_text="Date", margin=dict(t=40, r=0, l=0, b=0))
fig.update_xaxes(title="Time of Day")
return fig
When multiple sessions are present in filtered_session_df, the first one never displays the vrect and the vline. The annotation is plotted as expected.
This is very odd and I canβt understand why it would work for all the sessions but the 1st one. The print statements helped me confirm the session is there and the Plotstart and Plotend are correct and valid and included in the x range of the plot.
Does anyone know where this behaviour could coming from?
Thanks,