Skip to content

REF: avoid altering self.data in get_xticks #55906

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

Merged
merged 2 commits into from
Nov 10, 2023
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
28 changes: 11 additions & 17 deletions pandas/plotting/_matplotlib/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,15 +45,13 @@
)
from pandas.core.dtypes.generic import (
ABCDataFrame,
ABCDatetimeIndex,
ABCIndex,
ABCMultiIndex,
ABCPeriodIndex,
ABCSeries,
)
from pandas.core.dtypes.missing import (
isna,
notna,
)
from pandas.core.dtypes.missing import isna

import pandas.core.common as com
from pandas.core.frame import DataFrame
Expand Down Expand Up @@ -94,10 +92,7 @@
npt,
)

from pandas import (
PeriodIndex,
Series,
)
from pandas import Series


def _color_in_style(style: str) -> bool:
Expand Down Expand Up @@ -887,26 +882,25 @@ def plt(self):
_need_to_set_index = False

@final
def _get_xticks(self, convert_period: bool = False):
def _get_xticks(self):
index = self.data.index
is_datetype = index.inferred_type in ("datetime", "date", "datetime64", "time")

x: list[int] | np.ndarray
if self.use_index:
if convert_period and isinstance(index, ABCPeriodIndex):
self.data = self.data.reindex(index=index.sort_values())
index = cast("PeriodIndex", self.data.index)
if isinstance(index, ABCPeriodIndex):
# test_mixed_freq_irreg_period
x = index.to_timestamp()._mpl_repr()
# TODO: why do we need to do to_timestamp() here but not other
# places where we call mpl_repr?
elif is_any_real_numeric_dtype(index.dtype):
# Matplotlib supports numeric values or datetime objects as
# xaxis values. Taking LBYL approach here, by the time
# matplotlib raises exception when using non numeric/datetime
# values for xaxis, several actions are already taken by plt.
x = index._mpl_repr()
elif is_datetype:
self.data = self.data[notna(self.data.index)]
self.data = self.data.sort_index()
x = self.data.index._mpl_repr()
elif isinstance(index, ABCDatetimeIndex) or is_datetype:
x = index._mpl_repr()
else:
self._need_to_set_index = True
x = list(range(len(index)))
Expand Down Expand Up @@ -1434,7 +1428,7 @@ def _make_plot(self, fig: Figure) -> None:
plotf = self._ts_plot
it = data.items()
else:
x = self._get_xticks(convert_period=True)
x = self._get_xticks()
# error: Incompatible types in assignment (expression has type
# "Callable[[Any, Any, Any, Any, Any, Any, KwArg(Any)], Any]", variable has
# type "Callable[[Any, Any, Any, Any, KwArg(Any)], Any]")
Expand Down
19 changes: 15 additions & 4 deletions pandas/tests/plotting/frame/test_frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -1362,16 +1362,27 @@ def test_specified_props_kwd_plot_box(self, props, expected):
assert result[expected][0].get_color() == "C1"

def test_unordered_ts(self):
# GH#2609, GH#55906
index = [date(2012, 10, 1), date(2012, 9, 1), date(2012, 8, 1)]
values = [3.0, 2.0, 1.0]
df = DataFrame(
np.array([3.0, 2.0, 1.0]),
index=[date(2012, 10, 1), date(2012, 9, 1), date(2012, 8, 1)],
np.array(values),
index=index,
columns=["test"],
)
ax = df.plot()
xticks = ax.lines[0].get_xdata()
assert xticks[0] < xticks[1]
tm.assert_numpy_array_equal(xticks, np.array(index, dtype=object))
ydata = ax.lines[0].get_ydata()
tm.assert_numpy_array_equal(ydata, np.array([1.0, 2.0, 3.0]))
tm.assert_numpy_array_equal(ydata, np.array(values))

# even though we don't sort the data before passing it to matplotlib,
# the ticks are sorted
xticks = ax.xaxis.get_ticklabels()
xlocs = [x.get_position()[0] for x in xticks]
assert pd.Index(xlocs).is_monotonic_increasing
xlabels = [x.get_text() for x in xticks]
assert pd.to_datetime(xlabels, format="%Y-%m-%d").is_monotonic_increasing

@pytest.mark.parametrize("kind", plotting.PlotAccessor._common_kinds)
def test_kind_both_ways(self, kind):
Expand Down