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/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..58719b8 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,44 @@ 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"]), + ( + "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, 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 + + 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]