Skip to content
Merged
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
1 change: 1 addition & 0 deletions docs/app/uv.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions news/549.bugfix.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
`xy.pyplot` native mode now keeps calendar coordinates for pandas datetime-indexed `Series.plot()` / `DataFrame.plot()` under pandas 3.1, whose plotting paths pass raw period or business-day ordinals: daily, monthly, hourly and business-day indexes land on the native time axis in milliseconds since the epoch, while unrelated numeric overlays keep their units. pandas' minor period tickers are now ignored like its major ones, so PNG export no longer fails with `NotImplementedError`.
4 changes: 4 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,10 @@ dev = [
# `reflex` extra is installed in the main CI job.
"aiohttp>=3.14.3",
"uvicorn>=0.23",
# pandas datetime plotting is an optional *input* path through xy.pyplot,
# never a runtime dependency: the pandas regression tests and corpus case
# tests/pyplot/corpus/59_pandas_datetime_plot.py run where CI installs dev.
"pandas>=3",
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
# Parses .binder/environment.yml in tests/test_binder_config.py so the
# Binder contract is asserted on structure, not string transcription.
"pyyaml>=6",
Expand Down
48 changes: 48 additions & 0 deletions python/xy/pyplot/_axes.py
Original file line number Diff line number Diff line change
Expand Up @@ -674,6 +674,8 @@ def get_major_formatter(self) -> Any:

def set_minor_locator(self, locator: Any) -> None:
"""Set the locator used for the independent unlabeled minor tick set."""
if self._is_units_registry_ticker(locator):
return
host, key = self._ticker_slot()
host._tickers[(key, "minor_locator")] = locator
host._invalidate_shared_ticker_axis(key)
Expand All @@ -688,6 +690,8 @@ def get_transform(self) -> _ScaleTransformProxy:

def set_minor_formatter(self, formatter: Any) -> None:
"""Set a minor formatter, used when a labeled minor set is promoted."""
if self._is_units_registry_ticker(formatter):
return
host, key = self._ticker_slot()
host._tickers[(key, "minor_formatter")] = as_formatter(formatter, "set_minor_formatter()")
host._invalidate_shared_ticker_axis(key)
Expand Down Expand Up @@ -1999,6 +2003,7 @@ def plot(self, *args: Any, **kwargs: Any) -> list[Line2D]:

handles: list[Line2D] = []
for gx, gy, fmt in _iter_plot_groups(args):
gx = _restore_pandas_period_timestamps(self, gx)
gx, gy = np.atleast_1d(gx), np.atleast_1d(gy)
gx, gy = _convert_timedelta_axis(gx), _convert_timedelta_axis(gy)
# A 2-D operand draws one line per column; each column advances the
Expand Down Expand Up @@ -9562,6 +9567,49 @@ def _parse_date_text(value: str) -> Optional[np.datetime64]:
return None


def _restore_pandas_period_timestamps(ax: Any, values: Any) -> Any:
"""pandas' PeriodIndex ordinals → the timestamps they stand for, else ``values``.

pandas >= 3.1 plots a time series by handing ``ax.plot`` its
``PeriodIndex.asi8`` integer ordinals (older releases passed Period
objects, which `_convert_timedelta_axis` already maps). Those ordinals only
mean something through matplotlib's units registry, which this engine
deliberately omits: its time axis is native ms-since-epoch. pandas records
the series it is about to draw in ``ax._plot_data`` immediately before the
call, so restore timestamps only when the integers *are* that record's
index storage (shared memory) and its complete ordinal sequence. A later
numeric overlay whose values happen to equal period ordinals is ordinary
data and stays untouched. Duck-typed: the shim never imports pandas.
"""
if not isinstance(values, np.ndarray) or values.dtype != np.int64 or values.ndim != 1:
return values
records = getattr(ax, "_plot_data", None)
if not isinstance(records, list) or not records:
return values
record = records[-1]
index = getattr(record[0], "index", None) if isinstance(record, tuple) and record else None
to_timestamp = getattr(index, "to_timestamp", None)
freq = getattr(ax, "freq", None) # pandas' axis frequency: alias or offset
business_day = (freq if isinstance(freq, str) else getattr(freq, "name", None)) == "B"
if callable(to_timestamp):
ordinals = getattr(index, "asi8", None) # PeriodIndex storage
elif business_day:
# Business-day series skip Period[B] (deprecated): pandas plots an
# int64 Index of np.busday_count ordinals from 1970-01-01 instead.
ordinals = getattr(index, "_values", None)
else:
return values
if not isinstance(ordinals, np.ndarray) or ordinals.dtype != np.int64:
return values
if ordinals.shape != values.shape or not np.shares_memory(values, ordinals):
return values
if not np.array_equal(values, ordinals):
return values
if callable(to_timestamp):
return np.asarray(to_timestamp(how="start").to_numpy(), dtype="datetime64[ns]")
return np.busday_offset(np.datetime64("1970-01-01", "D"), values).astype("datetime64[ns]")


def _convert_timedelta_axis(values: np.ndarray) -> np.ndarray:
"""Map timedelta coordinates to seconds; dates and categories stay native."""
array = np.asanyarray(values)
Expand Down
9 changes: 7 additions & 2 deletions spec/matplotlib/compat.md
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,12 @@ dependency-free `triangles=` shorthand into Matplotlib's equivalent
`Triangulation` positional form; chart data and plotting options are unchanged.
PNG comparison captures the current figure at the end of each case. Examples
that need independent visual coverage belong in separate corpus files; the
datetime fill, shared-date axes, and removal scenarios each have their own case.
datetime fill, shared-date axes, removal, and pandas datetime-index scenarios
each have their own case. The pandas case is the corpus's one optional-input
dependency: pandas' plotting backend imports Matplotlib, so the runner's
`REQUIRES` table skips it where pandas or Matplotlib is absent and keeps it out
of the Matplotlib-blocked boundary run, while `xy.pyplot` itself stays
Matplotlib-free. pandas is installed with the `dev` group.

**The compat completion claim is gallery-defined.** The permanent contract
records the 507-source Matplotlib 3.11.1 documentation archive, excludes its
Expand Down Expand Up @@ -135,7 +140,7 @@ extended environment, thresholds, and completed report contract.
| `xlim` / `ylim`, `set_xmargin` / `set_ymargin`, axis scales, `invert_xaxis/yaxis` | linear/log are native; symlog/logit/asinh use dependency-free monotone data transforms with inverse limit/tick semantics. Automatic linear ticks include Matplotlib's 2.5 step and use uniform decimal padding across a tick set; locations refresh as data arrives. `axes.autolimit_mode="round_numbers"` expands automatic linear limits to the first and last AutoLocator ticks after applying the configured margins. Artist `get_data()` reflects the transformed space; logit masks values at/outside (0, 1) |
| `set_major_locator` / `set_major_formatter`, `plt.NullLocator/FixedLocator/MultipleLocator/MaxNLocator/LinearLocator/LogLocator`, `plt.NullFormatter/FixedFormatter/FuncFormatter/FormatStrFormatter/StrMethodFormatter/ScalarFormatter` | xy-owned re-implementations resolved at build time against live data limits (Null/Fixed/Multiple/Linear are position-exact; MaxN/Auto port Matplotlib's `MaxNLocator._raw_ticks` — same step tables, edge extension, and offset handling — with `nbins="auto"` budgeted from the estimated plot rect like `Axis.get_tick_space()`; Log remains approximate). Third-party locator objects work if they implement `tick_values(vmin, vmax)`; minor locators/formatters are retained for round-tripping but minor ticks do not render, except that a labeled minor pair under a blanked major formatter (the centered date-label idiom) is promoted to the drawn tick set |
| `plt.dates.MonthLocator/YearLocator/DayLocator/DateFormatter` | xy-owned equivalents of the `matplotlib.dates` classes gallery scripts use; they locate and format in the engine's canonical ms-since-epoch axis unit (not Matplotlib's day floats), and `interval` approximates rrule by epoch-anchored occurrence counting |
| datetime, timedelta, and string coordinates | datetime inputs use the engine's automatic date ticks, timedeltas are bounded to elapsed seconds, and common strings use categorical ticks; the general Matplotlib units registry is intentionally out of scope. pandas datetime plotting (`series.plot(ax=ax)`) works against that contract: `get_{x,y}data(orig=False)` returns ms-since-epoch floats, and pandas' period-ordinal tickers (`TimeSeries_Date*`) are accepted as no-ops so the native date ticks keep rendering |
| datetime, timedelta, and string coordinates | datetime inputs use the engine's automatic date ticks, timedeltas are bounded to elapsed seconds, and common strings use categorical ticks; the general Matplotlib units registry is intentionally out of scope. pandas datetime plotting (`series.plot(ax=ax)` / `frame.plot(ax=ax)`, pandas 3.0 and 3.1) works against that contract: pandas' period x coordinates map back to timestamps on the native time axis — Period objects (pandas 3.0) directly, and the integer ordinals pandas 3.1 passes (`PeriodIndex.asi8`, or business-day ordinals for `freq="B"`) only when the array shares storage with, and equals, the index pandas just recorded in `ax._plot_data`, so ordinary numeric overlays keep their units even when their values equal period ordinals. `get_{x,y}data(orig=False)` and limits use ms-since-epoch floats, and pandas' major and minor period-ordinal tickers (`TimeSeries_Date*`) are accepted as no-ops so the native date ticks keep rendering and export. pandas stays an optional input, never a runtime dependency (it is a dev dependency so CI exercises the path) |
| `xticks(positions, labels, rotation=)` / `tick_params(labelrotation=)` | Exact positions and strings render in browser, PNG, and SVG |
| `twinx()`, `secondary_xaxis()`, `secondary_yaxis()` | second data axes and linked tick-only secondary axes with callable forward/inverse conversions. Secondary-axis ticks are evenly spaced conversions of the primary domain (not Matplotlib's secondary-unit locators) and currently reach the interactive HTML client only — PNG/SVG export does not draw them yet |
| `fig, ax = plt.subplots()`; `plt.subplots(n, m, figsize=, dpi=, squeeze=, sharex=, sharey=)` | Grid renders as CSS-grid HTML and stitched PNG/SVG; shared axes use common domains and live linked pan/zoom. Shared x axes infer datetime units from any member of their all/row/column group, including panels with no x data; adding or removing date artists refreshes cached siblings without persisting an inferred axis type. Unrelated groups retain their own units. `Figure.subplots_adjust(left=, right=, top=, bottom=, wspace=, hspace=)` moves the SubplotParams frame: the grid resolves to explicit figure rectangles and every exporter (HTML, PNG, SVG) positions panels at those rectangles |
Expand Down
31 changes: 31 additions & 0 deletions tests/pyplot/corpus/59_pandas_datetime_plot.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
"""pandas datetime-indexed Series/DataFrame plots keep calendar x coordinates."""

import pathlib
import tempfile

import numpy as np
import pandas as pd

import xy.pyplot as plt

daily = pd.Series(
np.linspace(4000.0, 5000.0, 120),
index=pd.date_range("2012-01-01", periods=120, freq="D"),
)
monthly = pd.DataFrame(
{"north": np.linspace(1.0, 3.0, 24), "south": np.linspace(3.0, 1.0, 24)},
index=pd.date_range("2012-01-01", periods=24, freq="MS"),
)
hourly = pd.Series(
np.sin(np.linspace(0.0, 6.0, 72)),
index=pd.date_range("2012-01-01", periods=72, freq="h"),
)

fig, axes = plt.subplots(1, 3, figsize=(14, 4))
daily.plot(ax=axes[0], title="Daily Series")
monthly.plot(ax=axes[1], title="Monthly DataFrame")
hourly.plot(ax=axes[2], title="Hourly Series")

tmpdir = tempfile.TemporaryDirectory()
out_png = pathlib.Path(tmpdir.name) / "pandas-dates.png"
fig.savefig(out_png)
10 changes: 9 additions & 1 deletion tests/pyplot/test_boundaries.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
from pathlib import Path

import pytest
from tests.pyplot.test_corpus import REQUIRES

from xy.pyplot._translate import check_unsupported, not_implemented

Expand Down Expand Up @@ -106,8 +107,13 @@ def test_unsupported_errors_link_to_support_requests() -> None:


def test_complete_supported_corpus_runs_when_matplotlib_imports_fail() -> None:
"""Every advertised plotting method remains usable in dependency-free installs."""
"""Every advertised plotting method remains usable in dependency-free installs.

Snippets whose input library itself needs matplotlib (pandas' plotting
backend) are the only exclusions; the shim is still asserted
matplotlib-free by ``test_shim_import_stays_light``."""
corpus = Path(__file__).with_name("corpus")
needs_matplotlib = sorted(name for name, modules in REQUIRES.items() if "matplotlib" in modules)
_run_fresh(
f"""
import builtins
Expand All @@ -123,6 +129,8 @@ def blocked_import(name, *args, **kwargs):

import xy.pyplot as plt
for path in sorted(pathlib.Path({str(corpus)!r}).glob("[0-9][0-9]_*.py")):
if path.name in {needs_matplotlib!r}:
continue
runpy.run_path(path, run_name="__main__")
for figure in tuple(__import__("xy.pyplot._state", fromlist=["all_figures"]).all_figures()):
assert figure._repr_html_().startswith('<iframe class="xy-notebook-frame"')
Expand Down
20 changes: 18 additions & 2 deletions tests/pyplot/test_corpus.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,15 @@
# filename -> reason
XFAILS: dict[str, str] = {}

# Snippets whose *input* library needs packages the shim itself never imports:
# pandas' plotting backend imports matplotlib before it calls into ``ax``. They
# skip where those packages are absent and stay out of the matplotlib-blocked
# boundary run; xy.pyplot stays matplotlib-free either way.
# filename -> required importable modules
REQUIRES: dict[str, tuple[str, ...]] = {
"59_pandas_datetime_plot.py": ("pandas", "matplotlib"),
}

PNG_MAGIC = b"\x89PNG\r\n\x1a\n"
HTML_MAGIC = "<!doctype html>"
NOTEBOOK_HTML_MAGIC = '<iframe class="xy-notebook-frame"'
Expand Down Expand Up @@ -69,12 +78,19 @@ def _corpus_params() -> list[Any]:

def test_corpus_is_populated() -> None:
assert len(CORPUS) >= 35, f"corpus shrank to {len(CORPUS)} snippets"
unknown = set(XFAILS) - {p.name for p in CORPUS}
assert not unknown, f"XFAILS names missing snippets: {sorted(unknown)}"
unknown = (set(XFAILS) | set(REQUIRES)) - {p.name for p in CORPUS}
assert not unknown, f"XFAILS/REQUIRES name missing snippets: {sorted(unknown)}"


def require_snippet_inputs(path: pathlib.Path) -> None:
"""Skip a snippet whose declared input libraries are not installed."""
for module in REQUIRES.get(path.name, ()):
pytest.importorskip(module)


@pytest.mark.parametrize("path", _corpus_params())
def test_corpus_snippet(path: pathlib.Path) -> None:
require_snippet_inputs(path)
plt.close("all")
namespace: dict[str, Any] = {"__name__": "__main__", "__file__": str(path)}
try:
Expand Down
67 changes: 66 additions & 1 deletion tests/pyplot/test_pdsh_gap_features.py
Original file line number Diff line number Diff line change
Expand Up @@ -519,8 +519,17 @@ def _ms(stamp: str) -> float:
return float(np.datetime64(stamp, "ms").astype(np.int64))


def _pandas_plotting():
"""pandas, skipping where its plotting backend (matplotlib) is absent.

``Series.plot`` imports matplotlib before it calls into the xy axes; the
shim itself never does, so this path is optional in dev environments."""
pytest.importorskip("matplotlib")
return pytest.importorskip("pandas")


def test_pandas_datetime_series_plot_completes():
pd = pytest.importorskip("pandas")
pd = _pandas_plotting()
index = pd.date_range("2012-01-01", periods=120, freq="D")
series = pd.Series(np.linspace(4000.0, 5000.0, 120), index=index)
fig, ax = plt.subplots()
Expand All @@ -530,6 +539,62 @@ def test_pandas_datetime_series_plot_completes():
_png()


@pytest.mark.parametrize(
("freq", "periods"),
[("D", 120), ("MS", 24), ("h", 72), ("B", 40)],
ids=["daily", "monthly", "hourly", "business-day"],
)
@pytest.mark.parametrize("container", ["series", "frame"])
def test_pandas_period_index_plots_keep_calendar_coordinates(freq, periods, container):
# pandas >= 3.1 hands ax.plot() PeriodIndex.asi8 ordinals instead of Period
# objects (#549); they must still land on the native ms-since-epoch axis.
pd = _pandas_plotting()
index = pd.date_range("2012-01-01", periods=periods, freq=freq)
values = np.linspace(4000.0, 5000.0, periods)
if container == "series":
data = pd.Series(values, index=index)
else:
data = pd.DataFrame({"a": values, "b": values[::-1]}, index=index)
fig, ax = plt.subplots()
data.plot(ax=ax)
expected = index.values.astype("datetime64[ms]").astype(np.int64).astype(np.float64)
for line in ax.lines:
assert np.issubdtype(np.asarray(line.get_xdata()).dtype, np.datetime64)
np.testing.assert_array_equal(np.asarray(line.get_xdata(orig=False)), expected)
assert ax.get_xlim() == (expected[0], expected[-1])
_png(fig)


def test_numeric_overlay_after_pandas_period_plot_keeps_its_units():
# [0, 1, 2] equal the leading daily ordinals of a 1970-01-01 index, but they
# are the user's own numbers, not pandas' index storage: leave them alone.
pd = _pandas_plotting()
index = pd.date_range("1970-01-01", periods=3, freq="D")
fig, ax = plt.subplots()
pd.Series([1.0, 2.0, 3.0], index=index).plot(ax=ax)
(overlay,) = ax.plot(np.array([0, 1, 2], dtype=np.int64), [3.0, 2.0, 1.0])
assert list(np.asarray(overlay.get_xdata())) == [0, 1, 2]
assert ax.lines[0].get_xdata(orig=False)[1] == _ms("1970-01-02")


def test_pandas_minor_period_tickers_are_ignored():
pd = pytest.importorskip("pandas")
converter = pytest.importorskip("pandas.plotting._matplotlib.converter")
index = pd.date_range("2012-01-01", periods=30, freq="D")
freq = index.to_period("D").freq
fig, ax = plt.subplots()
ax.plot(index.values, np.arange(30.0))
ax.xaxis.set_minor_locator(
converter.TimeSeries_DateLocator(freq, minor_locator=True, plot_obj=None)
)
ax.xaxis.set_minor_formatter(
converter.TimeSeries_DateFormatter(freq, minor_locator=True, plot_obj=None)
)
assert isinstance(ax.xaxis.get_minor_locator(), plt.NullLocator)
assert isinstance(ax.xaxis.get_minor_formatter(), plt.NullFormatter)
_png(fig)


def test_get_xdata_orig_false_is_ms_since_epoch():
fig, ax = plt.subplots()
x = np.asarray(["2012-01-01", "NaT", "2012-01-03"], dtype="datetime64[ns]")
Expand Down
6 changes: 4 additions & 2 deletions tests/pyplot/test_reference_corpus.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,16 @@

import numpy as np
import pytest
from tests.pyplot.test_corpus import CORPUS
from tests.pyplot.test_corpus import CORPUS, require_snippet_inputs

import xy.pyplot as xyplt


def _adapt_reference_source(path: pathlib.Path, source: str) -> str:
"""Normalize the few intentional xy shorthand signatures for Matplotlib.

The source corpus remains dependency-free. Matplotlib's triangular APIs
The source corpus needs no plotting dependency beyond the engine under
test (pandas, a dev-group input library, feeds one case). Matplotlib's triangular APIs
require a ``Triangulation`` positional object where xy also accepts a
``triangles=`` keyword alongside x/y arrays.
"""
Expand Down Expand Up @@ -129,6 +130,7 @@ def _artifact_geometry(path: pathlib.Path) -> tuple[float, float]:

@pytest.mark.parametrize("path", CORPUS, ids=lambda path: path.name)
def test_corpus_in_isolated_reference_process(path: pathlib.Path, tmp_path: pathlib.Path) -> None:
require_snippet_inputs(path)
artifacts = {engine: tmp_path / f"{engine}.png" for engine in ("xy", "matplotlib")}
for engine, artifact in artifacts.items():
_run_engine(path, engine, artifact)
Expand Down
Loading
Loading