Thanks to visit codestin.com
Credit goes to github.com

Skip to content

[TST] Added test_axlines in test_datetime.py #27326

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

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
34 changes: 31 additions & 3 deletions lib/matplotlib/tests/test_datetime.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

import matplotlib.pyplot as plt
import matplotlib as mpl
from matplotlib.dates import date2num, DateFormatter


class TestDatetimePlotting:
Expand Down Expand Up @@ -77,11 +78,38 @@ def test_axhspan(self):
ax3.set_xlabel('Date')
ax3.set_ylabel('Date')

@pytest.mark.xfail(reason="Test for axline not written yet")
@mpl.style.context("default")
def test_axline(self):
fig, ax = plt.subplots()
ax.axline(...)
mpl.rcParams["date.converter"] = 'concise'
fig, (ax1, ax2, ax3) = plt.subplots(3, 1,
constrained_layout=True,
figsize=(10, 12))

start_date = datetime.datetime(2023, 1, 1)
dates = [start_date + datetime.timedelta(days=i) for i in range(31)]
values = list(range(1, 32))

ax1.plot(dates, values, 'ro')
ax1.axline((date2num(dates[0]), values[0]), (date2num(dates[-1]), values[-1]),
Copy link
Member

Choose a reason for hiding this comment

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

We specifically do not want to use date2num in these test cases. the fact that it is erroring when handed datetime objects is precisely the kind of thing we wanted to find out by implementing these tests.

The following patch gets most of the way to fixing it such that you can actually pass datetime objects (though I think it may need some consideration regarding what to do if a non-data transform is provided, or whether "slope" is something that can be meaningfully provided with unitful data):

diff --git a/lib/matplotlib/axes/_axes.py b/lib/matplotlib/axes/_axes.py
index 9199f1cafa..524c1ae06a 100644
--- a/lib/matplotlib/axes/_axes.py
+++ b/lib/matplotlib/axes/_axes.py
@@ -919,6 +919,9 @@ class Axes(_AxesBase):
                                   self.get_yscale() != 'linear'):
             raise TypeError("'slope' cannot be used with non-linear scales")
 
+        xy1 = tuple(self._process_unit_info([("x", xy1[0]), ("y", xy1[1])]))
+        if xy2 is not None:
+            xy2 = tuple(self._process_unit_info([("x", xy2[0]), ("y", xy2[1])]))
         datalim = [xy1] if xy2 is None else [xy1, xy2]
         if "transform" in kwargs:
             # if a transform is passed (i.e. line points not in data space),

Copy link
Member

Choose a reason for hiding this comment

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

I did the minimal change here to get the point-point version working with the default transform (data space). I do think that the final version would need at least some more.

  • passing kwargs in
  • Maybe pushing the unit transforming down into mlines.AxLine? (trying to trace how base Line2D does it, if that does it in the class, I'd probably follow suit for AxLine, but not super clear on that, actually... AxLine inherits from Line2D)
  • some more thought about slope may be good... it is already disallowed with non-linear scales, may be best to just disallow it with unitful data or declare it to be in explicitly "unitless data space" (currently it states that it is in 'data coordinates'). I think it may actually work out for at least the case of having the same units on both axes (i.e. the slope is unitless then) or possibly also with full unit libraries, though possibly would require pushing units into the AxLine class for it to work.

color='blue', linewidth=2)
ax1.set_title('Datetime vs. Number')
date_format = DateFormatter('%b%d')
ax1.xaxis.set_major_formatter(date_format)

ax2.plot(values, dates, 'ro')
ax2.axline((values[0], date2num(dates[0])), (values[-1], date2num(dates[-1])),
color='blue', linewidth=2)
ax2.set_title('Number vs. Datetime')
ax2.yaxis.set_major_formatter(date_format)

dates2 = [start_date + datetime.timedelta(days=2*i) for i in range(31)]
ax3.plot(dates, dates2, 'ro')
ax3.axline((date2num(dates[0]), date2num(dates2[0])),
(date2num(dates[-1]), date2num(dates2[-1])),
color='blue', linewidth=2)
ax3.set_title('Datetime vs. Datetime')
ax3.xaxis.set_major_formatter(date_format)
ax3.yaxis.set_major_formatter(date_format)

@mpl.style.context("default")
def test_axvline(self):
Expand Down