From 39a5a32dffed66c9db200be40df55b80784270dd Mon Sep 17 00:00:00 2001 From: Roberto Moura Date: Fri, 4 Dec 2026 04:01:28 +0000 Subject: [PATCH 1/2] Convert pandas time series values to dates pandas plots a regular time series at the ordinals of its periods, counted in the series' frequency since 1970, and formats the axis with its TimeSeries_DateFormatter. mpl_dates_to_datestrings treated these values as days since 1970 and converted them with matplotlib.dates.epoch2num, which matplotlib has since removed. The resulting AttributeError was caught and the values returned unchanged, so the x values and axis range stayed numbers on a date axis, which plotly reads as milliseconds since 1970: a daily series from 2001 ended up in the first seconds of 1970. Convert the ordinals with pandas' Period and the formatter's frequency instead, interpolating fractional ordinals such as bar edges within their period. This also fixes hourly, monthly and yearly series, which were wrong even with epoch2num because their ordinals are not days. To reach the frequency, pass the formatter itself rather than its class name to mpl_dates_to_datestrings. Warn if the conversion fails rather than returning the values silently. Remove the xfail mark from test_pandas_time_series_date_formatter and add tests for other frequencies and for fractional ordinals. --- matplotlylib/mpltools.py | 42 ++++++++++++++++++++++++++++++--------- matplotlylib/renderer.py | 4 +--- tests/test_date_times.py | 43 +++++++++++++++++++++++++++++++++++----- 3 files changed, 72 insertions(+), 17 deletions(-) diff --git a/matplotlylib/mpltools.py b/matplotlylib/mpltools.py index 4b9d3c2..6c33f5f 100644 --- a/matplotlylib/mpltools.py +++ b/matplotlylib/mpltools.py @@ -492,18 +492,19 @@ def prep_ticks(ax, index, ax_type, props): else: return dict() # get tick label formatting information - formatter = axis.get_major_formatter().__class__.__name__ + mpl_formatter = axis.get_major_formatter() + formatter = mpl_formatter.__class__.__name__ if ax_type == "x" and "DateFormatter" in formatter: axis_dict["type"] = "date" tickvalues = props["axes"][index]["tickvalues"] if tickvalues is not None: # custom ticks: export the exact locations and drop the # arithmetic tick0/dtick spec, which plotly would use instead - axis_dict["tickvals"] = mpl_dates_to_datestrings(tickvalues, formatter) + axis_dict["tickvals"] = mpl_dates_to_datestrings(tickvalues, mpl_formatter) axis_dict.pop("tick0", None) axis_dict.pop("dtick", None) axis_dict.pop("tickmode", None) - axis_dict["range"] = mpl_dates_to_datestrings(props["xlim"], formatter) + axis_dict["range"] = mpl_dates_to_datestrings(props["xlim"], mpl_formatter) if formatter == "LogFormatterMathtext": axis_dict["exponentformat"] = "e" @@ -571,6 +572,26 @@ def prep_xy_axis(ax, props, x_bounds, y_bounds): return xaxis, yaxis +def pandas_period_ordinals_to_datetimes(ordinals, freq): + """Convert pandas period ordinals to datetimes. + + pandas plots a regular time series at the ordinals of its periods, which + count periods of the series' frequency (days, hours, months, ...) since + 1970. A fractional ordinal is a position within its period, such as a bar + edge, so it is interpolated between the period's start and the next one's. + """ + import pandas as pd + + datetimes = [] + for ordinal in ordinals: + whole = math.floor(ordinal) + start = pd.Period(ordinal=whole, freq=freq).start_time + end = pd.Period(ordinal=whole + 1, freq=freq).start_time + timestamp = start + (ordinal - whole) * (end - start) + datetimes.append(timestamp.round("us").to_pydatetime()) + return datetimes + + def mpl_dates_to_datestrings(dates, mpl_formatter): """Convert matplotlib dates to iso-formatted-like time strings. @@ -581,13 +602,16 @@ def mpl_dates_to_datestrings(dates, mpl_formatter): """ _dates = dates - # this is a pandas datetime formatter, times show up in floating point days - # since the epoch (1970-01-01T00:00:00+00:00) - if mpl_formatter == "TimeSeries_DateFormatter": + # pandas formats regular time series with this formatter, and the values + # are its period ordinals rather than matplotlib dates + if type(mpl_formatter).__name__ == "TimeSeries_DateFormatter": try: - dates = matplotlib.dates.epoch2num([date * 24 * 60 * 60 for date in dates]) - dates = matplotlib.dates.num2date(dates) - except Exception: + dates = pandas_period_ordinals_to_datetimes(dates, mpl_formatter.freq) + except Exception as e: + warnings.warn( + "Could not convert pandas time series values to dates, " + "exporting them unchanged: {0}".format(e) + ) return _dates # the rest of mpl dates are in floating point days since diff --git a/matplotlylib/renderer.py b/matplotlylib/renderer.py index 41d23b0..b423aac 100644 --- a/matplotlylib/renderer.py +++ b/matplotlylib/renderer.py @@ -101,9 +101,7 @@ def __init__(self): def _convert_x_dates(self, x): """Convert x values to date strings when the x-axis is a date axis.""" if self.x_is_mpl_date: - formatter = ( - self.current_mpl_ax.get_xaxis().get_major_formatter().__class__.__name__ - ) + formatter = self.current_mpl_ax.get_xaxis().get_major_formatter() x = mpltools.mpl_dates_to_datestrings(x, formatter) return x diff --git a/tests/test_date_times.py b/tests/test_date_times.py index 4cbec40..76003e7 100644 --- a/tests/test_date_times.py +++ b/tests/test_date_times.py @@ -6,6 +6,7 @@ from matplotlib.dates import date2num from matplotlylib import mpl_to_plotly +from matplotlylib.mpltools import pandas_period_ordinals_to_datetimes def test_normal_mpl_dates(): @@ -32,11 +33,6 @@ def test_normal_mpl_dates(): assert list(trace.y) == [1, 2, 3, 4] -@pytest.mark.xfail( - strict=True, - reason="pandas time series plots keep matplotlib's day numbers as x values " - "on a date axis, so plotly reads them as milliseconds since 1970", -) def test_pandas_time_series_date_formatter(): df = pd.DataFrame( {"a": [0, 1, 2], "Date": pd.date_range("2001-01-01", periods=3, freq="D")} @@ -51,3 +47,40 @@ def test_pandas_time_series_date_formatter(): "2001-01-02 00:00:00", "2001-01-03 00:00:00", ] + assert list(plotly_fig.layout.xaxis.range) == [ + "2001-01-01 00:00:00", + "2001-01-03 00:00:00", + ] + + +@pytest.mark.parametrize( + "freq, expected_x", + [ + ("h", ["2001-01-01 00:00:00", "2001-01-01 01:00:00", "2001-01-01 02:00:00"]), + ("MS", ["2001-01-01 00:00:00", "2001-02-01 00:00:00", "2001-03-01 00:00:00"]), + ("YS", ["2001-01-01 00:00:00", "2002-01-01 00:00:00", "2003-01-01 00:00:00"]), + ], +) +def test_pandas_time_series_frequencies(freq, expected_x): + # pandas plots these at period ordinals counted in hours, months or years + # rather than days + index = pd.date_range("2001-01-01", periods=3, freq=freq) + fig = pd.DataFrame({"a": [0, 1, 2]}, index=index).plot().figure + + plotly_fig = mpl_to_plotly(fig) + + assert plotly_fig.layout.xaxis.type == "date" + assert list(plotly_fig.data[0].x) == expected_x + + +@pytest.mark.parametrize( + "ordinal, freq, expected", + [ + (11323, "D", datetime.datetime(2001, 1, 1)), + (11323.75, "D", datetime.datetime(2001, 1, 1, 18)), + # January has 31 days, so half of it is 15.5 days + (372.5, "M", datetime.datetime(2001, 1, 16, 12)), + ], +) +def test_pandas_period_ordinals_to_datetimes(ordinal, freq, expected): + assert pandas_period_ordinals_to_datetimes([ordinal], freq) == [expected] From e139b131867f5282ae6e96e00108b8c8c5254d01 Mon Sep 17 00:00:00 2001 From: Roberto Moura Date: Fri, 4 Dec 2026 04:02:22 +0000 Subject: [PATCH 2/2] Fix the axis domain of pandas time series in mplexporter mplexporter recognised pandas' PeriodConverter by importing it from pandas.tseries.converter, a module pandas no longer has. The ImportError was caught, so pandas axes fell through to num2date, which read the period ordinals as days since 1970. For an hourly series that put the domain in the year 2714, and for a 15-minute series the ordinals are past year 9999, so mpl_to_plotly raised a ValueError. Recognise the converter by its class name, as pandas has moved it between private modules, and add a 15-minute series to the frequency tests. --- matplotlylib/mplexporter/utils.py | 9 ++++----- tests/test_date_times.py | 8 ++++++-- 2 files changed, 10 insertions(+), 7 deletions(-) diff --git a/matplotlylib/mplexporter/utils.py b/matplotlylib/mplexporter/utils.py index 84bf950..761ce61 100644 --- a/matplotlylib/mplexporter/utils.py +++ b/matplotlylib/mplexporter/utils.py @@ -314,13 +314,12 @@ def get_axes_properties(ax): lim = domain if isinstance(axis.converter, matplotlib.dates.DateConverter): scale = "date" - try: + # pandas plots regular time series at period ordinals, which are not + # matplotlib dates. Recognize its converter by name, since pandas + # has moved the class between private modules. + if type(axis.converter).__name__ == "PeriodConverter": import pandas as pd - from pandas.tseries.converter import PeriodConverter - except ImportError: - pd = None - if pd is not None and isinstance(axis.converter, PeriodConverter): _dates = [pd.Period(ordinal=int(d), freq=axis.freq) for d in domain] domain = [ (d.year, d.month - 1, d.day, d.hour, d.minute, d.second, 0) diff --git a/tests/test_date_times.py b/tests/test_date_times.py index 76003e7..58719b8 100644 --- a/tests/test_date_times.py +++ b/tests/test_date_times.py @@ -57,13 +57,17 @@ def test_pandas_time_series_date_formatter(): "freq, expected_x", [ ("h", ["2001-01-01 00:00:00", "2001-01-01 01:00:00", "2001-01-01 02:00:00"]), + ( + "15min", + ["2001-01-01 00:00:00", "2001-01-01 00:15:00", "2001-01-01 00:30:00"], + ), ("MS", ["2001-01-01 00:00:00", "2001-02-01 00:00:00", "2001-03-01 00:00:00"]), ("YS", ["2001-01-01 00:00:00", "2002-01-01 00:00:00", "2003-01-01 00:00:00"]), ], ) def test_pandas_time_series_frequencies(freq, expected_x): - # pandas plots these at period ordinals counted in hours, months or years - # rather than days + # pandas plots these at period ordinals counted in hours, minutes, months + # or years rather than days index = pd.date_range("2001-01-01", periods=3, freq=freq) fig = pd.DataFrame({"a": [0, 1, 2]}, index=index).plot().figure