python - Plotly:当x轴显示日期时如何注释最大值?
问题描述
所以我有一个数据框(df_prod),其中包含一些光伏面板每小时发电量的时间序列。我有一个图表,想注释峰值。
我知道如何找到该值,但我不知道如何将峰值发生的日期作为注释的 x 值。我想我需要给它一个字符串,但我不确定。
这不起作用:
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
)
解决方案
当 index 为 a 时,这甚至适用于多个时间序列DatetimeIndex
:
fig.add_annotation(x=df.max(axis = 1).idxmax(),
y=df.max().max())
阴谋:
完整代码:
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()
推荐阅读
- for-loop - 如何在另一个命令之后在批处理脚本中删除 FOR 循环中的文件?
- kubernetes - 获取 Helm 依赖项的详细信息
- list - 是否有一种不可变的方法来将元组更改为在 scala 中列出?
- javascript - 删除所有用户控制 Facebook 视频嵌入
- hadoop - Hadoop 尝试使用 JDK 安装目录作为可执行命令
- woocommerce - WooCommerce Worldpay 购物者重定向 URL
- node.js - 如何停止被 Jest 中的调试器语句阻塞?
- javascript - 如果值 < 400,需要帮助返回更高的值
- android - 在片段中初始化 youtube 播放器片段
- python - 打印不带括号和逗号的列表(python)