Plotly: How to annotate maximum value when x axis displays dates?

Viewed 955

So i have a data frame (df_prod) with a time series of the hourly electricity production of some PV-panels. I have a graph and would like to annotate the peak value.

enter image description here

I know how to find the value, but I can't figure out how to put the date of when the peak happens as the x-value for the annotation. I think I need to give it a string, but I'm not sure.

This doesn't work:

for spal in df_prod.columns:
    maxvalue = df_prod[spal].max()
    fig.add_annotation(
    x = df_prod.index[df_prod[spal]==maxvalue],            # <--- this ist the problem
    y = wert,
    text='peak ' + spal + ': ' + str(f'{round(wert): n}') + ' kW',
    font={'size': 9} ,
    showarrow=True,
    arrowhead=3,
    xanchor='left',
    ax=20,
    ay=5,
    row=r, 
    col=c
)
1 Answers

This will work even with multiple time series when index is a DatetimeIndex:

fig.add_annotation(x=df.max(axis = 1).idxmax(),
                   y=df.max().max())

Plot:

enter image description here

Complete code:

import plotly.express as px
import numpy as np
from datetime import datetime
import pandas as pd
np.random.seed(23)
observations = 75
df=pd.DataFrame(dict(A=np.random.uniform(low=-1, high=1.1, size=observations).tolist(),
                    B=np.random.uniform(low=-1, high=1.1, size=observations).tolist(),
                    C=np.random.uniform(low=-1, high=1.1, size=observations).tolist(),
                    ))
df.iloc[0,] = 0
df = df.cumsum()

firstdate = datetime(2020,1,1)
df['date'] = pd.date_range(firstdate, periods=df.shape[0]).tolist()
df.set_index('date', inplace=True)

# fig.add_annotation(x=df.max(axis = 1).idxmax(),
#                    y=df.max().max())

fig = px.line(df, x = df.index, y = df.columns)

fig.add_annotation(showarrow=True,
                   arrowhead=1,
                   align = 'right',
                   x=df.max(axis = 1).idxmax(),
                   y=df.max().max(),
                   text="Max",
                   opacity=0.7)
f = fig.full_figure_for_development(warn=False)
fig.show()
Related