Roger Steinberg
Roger Steinberg

Reputation: 1604

Adding annotation text yields integer error message

When I adding a vline to my graph it works perfect:

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

[![enter image description here][1]][1]

When I try adding an annotation text alongside the vline I get an error message

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

TypeError: Addition/subtraction of integers and integer-arrays with Timestamp is no longer supported. Instead of adding/subtracting n, use n * obj.freq

Upvotes: 4

Views: 1840

Answers (1)

Rob Raymond
Rob Raymond

Reputation: 31166

  • as a workaround, do one call to add_vline() and one call to add_annotation()
  • have set parameters to add_annotation() such that annotation will be at top of line
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

enter image description here

sub-plots

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

enter image description here

Upvotes: 6

Related Questions