将“add_vline”注释文本垂直放置并在垂直线上居中

Dio*_*pra 7 python text position legend plotly

import plotly as plotly
from plotly.offline import plot
import plotly.express as px

import pandas as pd
import numpy as np

df = pd.DataFrame({'height': [712, 712, 716, 716, 718, np.nan, np.nan, np.nan, np.nan, np.nan],
                           'moisture ': [0.06, 0.19, 0.18, 0.17, 0.18, np.nan, np.nan, np.nan, np.nan, np.nan],
                           'tasks': ['water', None, None, 'prune', None, None, 'position', None, 'prune', None],
                           'weather': [None, 'humid', None, None, 'wet', None, None, None, None, 'hot']}, 
                           index=['2020-01-04', '2020-01-05', '2020-01-06', '2020-01-07', '2020-01-08', '2020-01-09',
                            '2020-01-10', '2020-01-11', '2020-01-12', '2020-01-13'])

df.index.name = 'date'
fig = px.line(df, y="height")

for x in df.loc[~df["tasks"].isna()].index:
    fig.add_vline(x=pd.to_datetime(x).timestamp() * 1000, line_width=1, line_dash="dash", line_color="red", annotation_text=df.loc[x, 'tasks'])

for x in df.loc[~df["weather"].isna()].index:
    fig.add_vline(x=pd.to_datetime(x).timestamp() * 1000, line_width=1, line_dash="dash", line_color="blue", annotation_text=df.loc[x, 'weather'])


fig.show()
Run Code Online (Sandbox Code Playgroud)

这会产生以下输出:

在此输入图像描述

我想将每条线的注释文本垂直放置在中点固定中心(向上的一半)

在文档中,我只能看到一个将注释放置在顶部或底部的选项,使用annotation_position

另外,由于这些行来自不同的列,我想添加一个图例以及单击以隐藏/显示列数据的功能(由“红色”和“蓝色”线表示)

提前谢谢了。

Rob*_*ond 7

您可以修改创建的注释add_vline()

import plotly as plotly
from plotly.offline import plot
import plotly.express as px

import pandas as pd
import numpy as np

df = pd.DataFrame({'height': [712, 712, 716, 716, 718, np.nan, np.nan, np.nan, np.nan, np.nan],
                           'moisture ': [0.06, 0.19, 0.18, 0.17, 0.18, np.nan, np.nan, np.nan, np.nan, np.nan],
                           'tasks': ['water', None, None, 'prune', None, None, 'position', None, 'prune', None],
                           'weather': [None, 'humid', None, None, 'wet', None, None, None, None, 'hot']}, 
                           index=['2020-01-04', '2020-01-05', '2020-01-06', '2020-01-07', '2020-01-08', '2020-01-09',
                            '2020-01-10', '2020-01-11', '2020-01-12', '2020-01-13'])

df.index.name = 'date'
fig = px.line(df, y="height")

for x in df.loc[~df["tasks"].isna()].index:
    fig.add_vline(x=pd.to_datetime(x).timestamp() * 1000, line_width=1, line_dash="dash", line_color="red", annotation_text=df.loc[x, 'tasks'])

for x in df.loc[~df["weather"].isna()].index:
    fig.add_vline(x=pd.to_datetime(x).timestamp() * 1000, line_width=1, line_dash="dash", line_color="blue", annotation_text=df.loc[x, 'weather'])


fig.update_layout(annotations=[{**a, **{"y":.5}}  for a in fig.to_dict()["layout"]["annotations"]])
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述