Skip to content

Comments

Fix add_vline and add_hline with datetime axes#5508

Open
mosh3eb wants to merge 1 commit intoplotly:mainfrom
mosh3eb:fix/add-vline-datetime-annotation
Open

Fix add_vline and add_hline with datetime axes#5508
mosh3eb wants to merge 1 commit intoplotly:mainfrom
mosh3eb:fix/add-vline-datetime-annotation

Conversation

@mosh3eb
Copy link

@mosh3eb mosh3eb commented Feb 14, 2026

Summary

When using add_vline, add_hline, add_vrect, or add_hrect with annotation_text on datetime axes, plotly crashes with a TypeError because the _mean() helper function tries to call float(sum(x)) on datetime strings.

Approach

Instead of assuming input values are equal (which only works for vlines/hlines), _mean() now converts datetime-like values to milliseconds-since-epoch, computes the actual arithmetic mean, and converts back. This correctly handles annotation placement for ALL shapes with datetime axes, including rects where x0 != x1.

  • The numeric fast path is unchanged -- datetime handling only activates when sum() raises TypeError
  • Handles both date strings ("2018-09-24") and datetime.datetime objects
  • Re-raises TypeError for truly unsupported types

Changes

  • plotly/shapeannotation.py: Added _is_date_string(), _datetime_str_to_ms(), _ms_to_datetime_str() helpers and updated _mean() with try/except fallback
  • tests/test_optional/test_autoshapes/test_annotated_shapes.py: Added 5 tests covering datetime strings, datetime objects, vlines, hlines, and vrects

Fixes #3065

@emilykl
Copy link
Contributor

emilykl commented Feb 19, 2026

Thanks for the contribution @mosh3eb ! This approach won't work because the _mean() function is used to determine annotation placement for ALL lines, not just vertical/horizontal lines, so we can't assume that the input values are equal. See the linked issue for further discussion of possible fixes.

@emilykl emilykl self-assigned this Feb 19, 2026
Instead of assuming input values are equal, _mean() now converts
datetime-like values (date strings and datetime objects) to
milliseconds-since-epoch, computes the actual arithmetic mean, and
converts back. This correctly handles annotation placement for ALL
shapes (vlines, hlines, vrects, hrects) with datetime axes.

The numeric fast path is unchanged — datetime handling only activates
when sum() raises TypeError on non-numeric types.

Added tests for datetime strings, datetime objects, and rects with
different x0/x1 values on datetime axes.

Fixes plotly#3065
@mosh3eb mosh3eb force-pushed the fix/add-vline-datetime-annotation branch 2 times, most recently from c580b1f to 9bed9d3 Compare February 20, 2026 23:34
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Error on using add_vline with text annotation for data with date-time x axis

2 participants