Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix xvals for datetime axis #210

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file modified labellines/baseline/test_dateaxis_advanced.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
19 changes: 19 additions & 0 deletions labellines/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

import matplotlib.pyplot as plt
import numpy as np
from datetime import datetime
from matplotlib.container import ErrorbarContainer
from matplotlib.dates import DateConverter, num2date
from matplotlib.lines import Line2D
Expand Down Expand Up @@ -186,18 +187,34 @@ def labelLines(
if isinstance(xvals, tuple) and len(xvals) == 2:
xmin, xmax = xvals
xscale = ax.get_xscale()

# Convert datetime objects to numeric values for linspace/geomspace
x_is_datetime = isinstance(xmin, datetime) or isinstance(xmax, datetime)
if x_is_datetime:
if not isinstance(xmin, datetime) or not isinstance(xmax, datetime):
raise ValueError(
f"Cannot mix datetime and numeric values in xvals: {xvals}"
)
xmin = plt.matplotlib.dates.date2num(xmin)
xmax = plt.matplotlib.dates.date2num(xmax)

if xscale == "log":
xvals = np.geomspace(xmin, xmax, len(all_lines) + 2)[1:-1]
else:
xvals = np.linspace(xmin, xmax, len(all_lines) + 2)[1:-1]

# Convert numeric values back to datetime objects
if x_is_datetime:
xvals = plt.matplotlib.dates.num2date(xvals)

# Build matrix line -> xvalue
ok_matrix = np.zeros((len(all_lines), len(all_lines)), dtype=bool)

for i, line in enumerate(all_lines):
xdata, _ = normalize_xydata(line)
minx, maxx = min(xdata), max(xdata)
for j, xv in enumerate(xvals): # type: ignore
xv = line.convert_xunits(xv)
ok_matrix[i, j] = minx < xv < maxx

# If some xvals do not fall in their corresponding line,
Expand All @@ -224,6 +241,8 @@ def labelLines(
# Move xlabel if it is outside valid range
xdata, _ = normalize_xydata(line)
xmin, xmax = min(xdata), max(xdata)
xv = line.convert_xunits(xv)

if not (xmin <= xv <= xmax):
warnings.warn(
(
Expand Down
2 changes: 1 addition & 1 deletion labellines/test.py
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,7 @@ def test_dateaxis_advanced(setup_mpl):
ax.xaxis.set_major_locator(DayLocator())
ax.xaxis.set_major_formatter(DateFormatter("%Y-%m-%d"))

labelLines(ax.get_lines())
labelLines(ax.get_lines(), xvals=(dates[0], dates[-1]))
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Shouldn't this place the first label on 2018/11/01 and the second on 2018/11/03?

Copy link
Contributor Author

@scottshambaugh scottshambaugh Mar 8, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That's true for a list input xvals=[dates[0], dates[-1]], but the tuple input adds padding equivalent to a blank label at the extremes automatically

return plt.gcf()


Expand Down