添加注记文本会产生整型错误消息

2022-04-19 00:00:00 python plotly plotly-dash

问题描述

当我将vline添加到我的图形时,它工作得很好:

fig.add_vline(
        x=pd.to_datetime('1970-01-01 00:00:00'),
        line_dash='dot',
        row=0)

[![在此处输入图片描述][1]][1]

当我尝试在vline旁边添加批注文本时,收到错误消息

fig.add_vline(
    x=pd.to_datetime('1970-01-01 00:00:00'),
    line_dash='dot',
    annotation_text='15',
    row=0)
TypeError:整数和整数数组的加/减 不再支持时间戳。不是加/减[2-0], 使用n * obj.freq


解决方案

  • 作为一种解决办法,对add_vline()调用一次,对add_annotation()调用一次
  • 已将参数设置为add_annotation(),以便批注位于行首
import pandas as pd
import plotly.express as px

ROWS = 20
df = pd.DataFrame({"ColA":pd.date_range("1-jan-1970", freq="4H", periods=ROWS), "ColB":np.random.uniform(1,30, ROWS)})

fig = px.line(df, x="ColA", y="ColB")
fig.update_xaxes(title_font=dict(size=12), tickformat='%X')

for time in df["ColA"].values:
    time = pd.Timestamp(time).to_pydatetime()
    fig.add_vline(x=time)
    fig.add_annotation(x=time, y=1, yref="paper", text="15")

fig

子图

import pandas as pd
import plotly.express as px

ROWS = 20
df = pd.DataFrame(
    {
        "ColA": pd.date_range("1-jan-1970", freq="4H", periods=ROWS),
        "ColB": np.random.uniform(1, 30, ROWS),
        "Facet": np.repeat(["plot 1", "plot 2"], ROWS // 2),
    }
)

fig = px.line(df, x="ColA", y="ColB", facet_row="Facet")
fig.update_xaxes(title_font=dict(size=12), tickformat="%X")

for time, y, facet in df[["ColA", "ColB", "Facet"]].values:
    time = pd.Timestamp(time).to_pydatetime()
    fig.add_vline(x=time, row=0 if facet == "plot 1" else 1)
    fig.add_annotation(x=time, y=y, text="15", row=0 if facet == "plot 1" else 1, col=0)

fig

相关文章