applied-ai-018 commited on
Commit
63339f2
·
verified ·
1 Parent(s): eb90dde

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. ckpts/llama-3b/global_step100/bf16_zero_pp_rank_13_mp_rank_02_optim_states.pt +3 -0
  2. ckpts/llama-3b/global_step100/bf16_zero_pp_rank_184_mp_rank_03_optim_states.pt +3 -0
  3. ckpts/llama-3b/global_step100/bf16_zero_pp_rank_217_mp_rank_01_optim_states.pt +3 -0
  4. ckpts/llama-3b/global_step100/bf16_zero_pp_rank_35_mp_rank_01_optim_states.pt +3 -0
  5. venv/lib/python3.10/site-packages/pandas/plotting/__pycache__/__init__.cpython-310.pyc +0 -0
  6. venv/lib/python3.10/site-packages/pandas/plotting/__pycache__/_core.cpython-310.pyc +0 -0
  7. venv/lib/python3.10/site-packages/pandas/plotting/_matplotlib/__init__.py +93 -0
  8. venv/lib/python3.10/site-packages/pandas/plotting/_matplotlib/__pycache__/__init__.cpython-310.pyc +0 -0
  9. venv/lib/python3.10/site-packages/pandas/plotting/_matplotlib/__pycache__/boxplot.cpython-310.pyc +0 -0
  10. venv/lib/python3.10/site-packages/pandas/plotting/_matplotlib/__pycache__/converter.cpython-310.pyc +0 -0
  11. venv/lib/python3.10/site-packages/pandas/plotting/_matplotlib/__pycache__/core.cpython-310.pyc +0 -0
  12. venv/lib/python3.10/site-packages/pandas/plotting/_matplotlib/__pycache__/groupby.cpython-310.pyc +0 -0
  13. venv/lib/python3.10/site-packages/pandas/plotting/_matplotlib/__pycache__/hist.cpython-310.pyc +0 -0
  14. venv/lib/python3.10/site-packages/pandas/plotting/_matplotlib/__pycache__/misc.cpython-310.pyc +0 -0
  15. venv/lib/python3.10/site-packages/pandas/plotting/_matplotlib/__pycache__/style.cpython-310.pyc +0 -0
  16. venv/lib/python3.10/site-packages/pandas/plotting/_matplotlib/__pycache__/timeseries.cpython-310.pyc +0 -0
  17. venv/lib/python3.10/site-packages/pandas/plotting/_matplotlib/__pycache__/tools.cpython-310.pyc +0 -0
  18. venv/lib/python3.10/site-packages/pandas/plotting/_matplotlib/boxplot.py +572 -0
  19. venv/lib/python3.10/site-packages/pandas/plotting/_matplotlib/converter.py +1135 -0
  20. venv/lib/python3.10/site-packages/pandas/plotting/_matplotlib/core.py +2119 -0
  21. venv/lib/python3.10/site-packages/pandas/plotting/_matplotlib/groupby.py +142 -0
  22. venv/lib/python3.10/site-packages/pandas/plotting/_matplotlib/hist.py +581 -0
  23. venv/lib/python3.10/site-packages/pandas/plotting/_matplotlib/misc.py +481 -0
  24. venv/lib/python3.10/site-packages/pandas/plotting/_matplotlib/style.py +278 -0
  25. venv/lib/python3.10/site-packages/pandas/plotting/_matplotlib/timeseries.py +370 -0
  26. venv/lib/python3.10/site-packages/pandas/plotting/_matplotlib/tools.py +492 -0
  27. venv/lib/python3.10/site-packages/pandas/tests/__pycache__/__init__.cpython-310.pyc +0 -0
  28. venv/lib/python3.10/site-packages/pandas/tests/__pycache__/test_aggregation.cpython-310.pyc +0 -0
  29. venv/lib/python3.10/site-packages/pandas/tests/__pycache__/test_algos.cpython-310.pyc +0 -0
  30. venv/lib/python3.10/site-packages/pandas/tests/__pycache__/test_common.cpython-310.pyc +0 -0
  31. venv/lib/python3.10/site-packages/pandas/tests/__pycache__/test_downstream.cpython-310.pyc +0 -0
  32. venv/lib/python3.10/site-packages/pandas/tests/__pycache__/test_errors.cpython-310.pyc +0 -0
  33. venv/lib/python3.10/site-packages/pandas/tests/__pycache__/test_expressions.cpython-310.pyc +0 -0
  34. venv/lib/python3.10/site-packages/pandas/tests/__pycache__/test_flags.cpython-310.pyc +0 -0
  35. venv/lib/python3.10/site-packages/pandas/tests/__pycache__/test_multilevel.cpython-310.pyc +0 -0
  36. venv/lib/python3.10/site-packages/pandas/tests/__pycache__/test_nanops.cpython-310.pyc +0 -0
  37. venv/lib/python3.10/site-packages/pandas/tests/__pycache__/test_optional_dependency.cpython-310.pyc +0 -0
  38. venv/lib/python3.10/site-packages/pandas/tests/__pycache__/test_register_accessor.cpython-310.pyc +0 -0
  39. venv/lib/python3.10/site-packages/pandas/tests/__pycache__/test_sorting.cpython-310.pyc +0 -0
  40. venv/lib/python3.10/site-packages/pandas/tests/__pycache__/test_take.cpython-310.pyc +0 -0
  41. venv/lib/python3.10/site-packages/pandas/tests/base/__init__.py +0 -0
  42. venv/lib/python3.10/site-packages/pandas/tests/base/__pycache__/__init__.cpython-310.pyc +0 -0
  43. venv/lib/python3.10/site-packages/pandas/tests/base/__pycache__/common.cpython-310.pyc +0 -0
  44. venv/lib/python3.10/site-packages/pandas/tests/base/__pycache__/test_constructors.cpython-310.pyc +0 -0
  45. venv/lib/python3.10/site-packages/pandas/tests/base/__pycache__/test_conversion.cpython-310.pyc +0 -0
  46. venv/lib/python3.10/site-packages/pandas/tests/base/__pycache__/test_fillna.cpython-310.pyc +0 -0
  47. venv/lib/python3.10/site-packages/pandas/tests/base/__pycache__/test_misc.cpython-310.pyc +0 -0
  48. venv/lib/python3.10/site-packages/pandas/tests/base/__pycache__/test_transpose.cpython-310.pyc +0 -0
  49. venv/lib/python3.10/site-packages/pandas/tests/base/__pycache__/test_unique.cpython-310.pyc +0 -0
  50. venv/lib/python3.10/site-packages/pandas/tests/base/__pycache__/test_value_counts.cpython-310.pyc +0 -0
ckpts/llama-3b/global_step100/bf16_zero_pp_rank_13_mp_rank_02_optim_states.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c750018c2e17fc64bedda06f49a605de1205b9816105b4c1722fc13c1fedb304
3
+ size 41830330
ckpts/llama-3b/global_step100/bf16_zero_pp_rank_184_mp_rank_03_optim_states.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d6351546e4ec255305c11fdda0e2dbc59c084b16e834684d4f39785287846e8b
3
+ size 41830340
ckpts/llama-3b/global_step100/bf16_zero_pp_rank_217_mp_rank_01_optim_states.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:74d1c34395045bd259106a2b2aff837960ca1cabf3471137988d0c3a1ef9a5c9
3
+ size 41830148
ckpts/llama-3b/global_step100/bf16_zero_pp_rank_35_mp_rank_01_optim_states.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:185700df1bd72fef4ff2c39c043aee39beb49b0a59569ecf30566b1c1a4d0465
3
+ size 41830138
venv/lib/python3.10/site-packages/pandas/plotting/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (2.8 kB). View file
 
venv/lib/python3.10/site-packages/pandas/plotting/__pycache__/_core.cpython-310.pyc ADDED
Binary file (61.2 kB). View file
 
venv/lib/python3.10/site-packages/pandas/plotting/_matplotlib/__init__.py ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from typing import TYPE_CHECKING
4
+
5
+ from pandas.plotting._matplotlib.boxplot import (
6
+ BoxPlot,
7
+ boxplot,
8
+ boxplot_frame,
9
+ boxplot_frame_groupby,
10
+ )
11
+ from pandas.plotting._matplotlib.converter import (
12
+ deregister,
13
+ register,
14
+ )
15
+ from pandas.plotting._matplotlib.core import (
16
+ AreaPlot,
17
+ BarhPlot,
18
+ BarPlot,
19
+ HexBinPlot,
20
+ LinePlot,
21
+ PiePlot,
22
+ ScatterPlot,
23
+ )
24
+ from pandas.plotting._matplotlib.hist import (
25
+ HistPlot,
26
+ KdePlot,
27
+ hist_frame,
28
+ hist_series,
29
+ )
30
+ from pandas.plotting._matplotlib.misc import (
31
+ andrews_curves,
32
+ autocorrelation_plot,
33
+ bootstrap_plot,
34
+ lag_plot,
35
+ parallel_coordinates,
36
+ radviz,
37
+ scatter_matrix,
38
+ )
39
+ from pandas.plotting._matplotlib.tools import table
40
+
41
+ if TYPE_CHECKING:
42
+ from pandas.plotting._matplotlib.core import MPLPlot
43
+
44
+ PLOT_CLASSES: dict[str, type[MPLPlot]] = {
45
+ "line": LinePlot,
46
+ "bar": BarPlot,
47
+ "barh": BarhPlot,
48
+ "box": BoxPlot,
49
+ "hist": HistPlot,
50
+ "kde": KdePlot,
51
+ "area": AreaPlot,
52
+ "pie": PiePlot,
53
+ "scatter": ScatterPlot,
54
+ "hexbin": HexBinPlot,
55
+ }
56
+
57
+
58
+ def plot(data, kind, **kwargs):
59
+ # Importing pyplot at the top of the file (before the converters are
60
+ # registered) causes problems in matplotlib 2 (converters seem to not
61
+ # work)
62
+ import matplotlib.pyplot as plt
63
+
64
+ if kwargs.pop("reuse_plot", False):
65
+ ax = kwargs.get("ax")
66
+ if ax is None and len(plt.get_fignums()) > 0:
67
+ with plt.rc_context():
68
+ ax = plt.gca()
69
+ kwargs["ax"] = getattr(ax, "left_ax", ax)
70
+ plot_obj = PLOT_CLASSES[kind](data, **kwargs)
71
+ plot_obj.generate()
72
+ plot_obj.draw()
73
+ return plot_obj.result
74
+
75
+
76
+ __all__ = [
77
+ "plot",
78
+ "hist_series",
79
+ "hist_frame",
80
+ "boxplot",
81
+ "boxplot_frame",
82
+ "boxplot_frame_groupby",
83
+ "table",
84
+ "andrews_curves",
85
+ "autocorrelation_plot",
86
+ "bootstrap_plot",
87
+ "lag_plot",
88
+ "parallel_coordinates",
89
+ "radviz",
90
+ "scatter_matrix",
91
+ "register",
92
+ "deregister",
93
+ ]
venv/lib/python3.10/site-packages/pandas/plotting/_matplotlib/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (1.88 kB). View file
 
venv/lib/python3.10/site-packages/pandas/plotting/_matplotlib/__pycache__/boxplot.cpython-310.pyc ADDED
Binary file (13.4 kB). View file
 
venv/lib/python3.10/site-packages/pandas/plotting/_matplotlib/__pycache__/converter.cpython-310.pyc ADDED
Binary file (29 kB). View file
 
venv/lib/python3.10/site-packages/pandas/plotting/_matplotlib/__pycache__/core.cpython-310.pyc ADDED
Binary file (50 kB). View file
 
venv/lib/python3.10/site-packages/pandas/plotting/_matplotlib/__pycache__/groupby.cpython-310.pyc ADDED
Binary file (4.35 kB). View file
 
venv/lib/python3.10/site-packages/pandas/plotting/_matplotlib/__pycache__/hist.cpython-310.pyc ADDED
Binary file (12.8 kB). View file
 
venv/lib/python3.10/site-packages/pandas/plotting/_matplotlib/__pycache__/misc.cpython-310.pyc ADDED
Binary file (11.5 kB). View file
 
venv/lib/python3.10/site-packages/pandas/plotting/_matplotlib/__pycache__/style.cpython-310.pyc ADDED
Binary file (8.82 kB). View file
 
venv/lib/python3.10/site-packages/pandas/plotting/_matplotlib/__pycache__/timeseries.cpython-310.pyc ADDED
Binary file (8.05 kB). View file
 
venv/lib/python3.10/site-packages/pandas/plotting/_matplotlib/__pycache__/tools.cpython-310.pyc ADDED
Binary file (11.8 kB). View file
 
venv/lib/python3.10/site-packages/pandas/plotting/_matplotlib/boxplot.py ADDED
@@ -0,0 +1,572 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from typing import (
4
+ TYPE_CHECKING,
5
+ Literal,
6
+ NamedTuple,
7
+ )
8
+ import warnings
9
+
10
+ from matplotlib.artist import setp
11
+ import numpy as np
12
+
13
+ from pandas._libs import lib
14
+ from pandas.util._decorators import cache_readonly
15
+ from pandas.util._exceptions import find_stack_level
16
+
17
+ from pandas.core.dtypes.common import is_dict_like
18
+ from pandas.core.dtypes.generic import ABCSeries
19
+ from pandas.core.dtypes.missing import remove_na_arraylike
20
+
21
+ import pandas as pd
22
+ import pandas.core.common as com
23
+
24
+ from pandas.io.formats.printing import pprint_thing
25
+ from pandas.plotting._matplotlib.core import (
26
+ LinePlot,
27
+ MPLPlot,
28
+ )
29
+ from pandas.plotting._matplotlib.groupby import create_iter_data_given_by
30
+ from pandas.plotting._matplotlib.style import get_standard_colors
31
+ from pandas.plotting._matplotlib.tools import (
32
+ create_subplots,
33
+ flatten_axes,
34
+ maybe_adjust_figure,
35
+ )
36
+
37
+ if TYPE_CHECKING:
38
+ from collections.abc import Collection
39
+
40
+ from matplotlib.axes import Axes
41
+ from matplotlib.figure import Figure
42
+ from matplotlib.lines import Line2D
43
+
44
+ from pandas._typing import MatplotlibColor
45
+
46
+
47
+ def _set_ticklabels(ax: Axes, labels: list[str], is_vertical: bool, **kwargs) -> None:
48
+ """Set the tick labels of a given axis.
49
+
50
+ Due to https://github.com/matplotlib/matplotlib/pull/17266, we need to handle the
51
+ case of repeated ticks (due to `FixedLocator`) and thus we duplicate the number of
52
+ labels.
53
+ """
54
+ ticks = ax.get_xticks() if is_vertical else ax.get_yticks()
55
+ if len(ticks) != len(labels):
56
+ i, remainder = divmod(len(ticks), len(labels))
57
+ assert remainder == 0, remainder
58
+ labels *= i
59
+ if is_vertical:
60
+ ax.set_xticklabels(labels, **kwargs)
61
+ else:
62
+ ax.set_yticklabels(labels, **kwargs)
63
+
64
+
65
+ class BoxPlot(LinePlot):
66
+ @property
67
+ def _kind(self) -> Literal["box"]:
68
+ return "box"
69
+
70
+ _layout_type = "horizontal"
71
+
72
+ _valid_return_types = (None, "axes", "dict", "both")
73
+
74
+ class BP(NamedTuple):
75
+ # namedtuple to hold results
76
+ ax: Axes
77
+ lines: dict[str, list[Line2D]]
78
+
79
+ def __init__(self, data, return_type: str = "axes", **kwargs) -> None:
80
+ if return_type not in self._valid_return_types:
81
+ raise ValueError("return_type must be {None, 'axes', 'dict', 'both'}")
82
+
83
+ self.return_type = return_type
84
+ # Do not call LinePlot.__init__ which may fill nan
85
+ MPLPlot.__init__(self, data, **kwargs) # pylint: disable=non-parent-init-called
86
+
87
+ if self.subplots:
88
+ # Disable label ax sharing. Otherwise, all subplots shows last
89
+ # column label
90
+ if self.orientation == "vertical":
91
+ self.sharex = False
92
+ else:
93
+ self.sharey = False
94
+
95
+ # error: Signature of "_plot" incompatible with supertype "MPLPlot"
96
+ @classmethod
97
+ def _plot( # type: ignore[override]
98
+ cls, ax: Axes, y: np.ndarray, column_num=None, return_type: str = "axes", **kwds
99
+ ):
100
+ ys: np.ndarray | list[np.ndarray]
101
+ if y.ndim == 2:
102
+ ys = [remove_na_arraylike(v) for v in y]
103
+ # Boxplot fails with empty arrays, so need to add a NaN
104
+ # if any cols are empty
105
+ # GH 8181
106
+ ys = [v if v.size > 0 else np.array([np.nan]) for v in ys]
107
+ else:
108
+ ys = remove_na_arraylike(y)
109
+ bp = ax.boxplot(ys, **kwds)
110
+
111
+ if return_type == "dict":
112
+ return bp, bp
113
+ elif return_type == "both":
114
+ return cls.BP(ax=ax, lines=bp), bp
115
+ else:
116
+ return ax, bp
117
+
118
+ def _validate_color_args(self, color, colormap):
119
+ if color is lib.no_default:
120
+ return None
121
+
122
+ if colormap is not None:
123
+ warnings.warn(
124
+ "'color' and 'colormap' cannot be used "
125
+ "simultaneously. Using 'color'",
126
+ stacklevel=find_stack_level(),
127
+ )
128
+
129
+ if isinstance(color, dict):
130
+ valid_keys = ["boxes", "whiskers", "medians", "caps"]
131
+ for key in color:
132
+ if key not in valid_keys:
133
+ raise ValueError(
134
+ f"color dict contains invalid key '{key}'. "
135
+ f"The key must be either {valid_keys}"
136
+ )
137
+ return color
138
+
139
+ @cache_readonly
140
+ def _color_attrs(self):
141
+ # get standard colors for default
142
+ # use 2 colors by default, for box/whisker and median
143
+ # flier colors isn't needed here
144
+ # because it can be specified by ``sym`` kw
145
+ return get_standard_colors(num_colors=3, colormap=self.colormap, color=None)
146
+
147
+ @cache_readonly
148
+ def _boxes_c(self):
149
+ return self._color_attrs[0]
150
+
151
+ @cache_readonly
152
+ def _whiskers_c(self):
153
+ return self._color_attrs[0]
154
+
155
+ @cache_readonly
156
+ def _medians_c(self):
157
+ return self._color_attrs[2]
158
+
159
+ @cache_readonly
160
+ def _caps_c(self):
161
+ return self._color_attrs[0]
162
+
163
+ def _get_colors(
164
+ self,
165
+ num_colors=None,
166
+ color_kwds: dict[str, MatplotlibColor]
167
+ | MatplotlibColor
168
+ | Collection[MatplotlibColor]
169
+ | None = "color",
170
+ ) -> None:
171
+ pass
172
+
173
+ def maybe_color_bp(self, bp) -> None:
174
+ if isinstance(self.color, dict):
175
+ boxes = self.color.get("boxes", self._boxes_c)
176
+ whiskers = self.color.get("whiskers", self._whiskers_c)
177
+ medians = self.color.get("medians", self._medians_c)
178
+ caps = self.color.get("caps", self._caps_c)
179
+ else:
180
+ # Other types are forwarded to matplotlib
181
+ # If None, use default colors
182
+ boxes = self.color or self._boxes_c
183
+ whiskers = self.color or self._whiskers_c
184
+ medians = self.color or self._medians_c
185
+ caps = self.color or self._caps_c
186
+
187
+ color_tup = (boxes, whiskers, medians, caps)
188
+ maybe_color_bp(bp, color_tup=color_tup, **self.kwds)
189
+
190
+ def _make_plot(self, fig: Figure) -> None:
191
+ if self.subplots:
192
+ self._return_obj = pd.Series(dtype=object)
193
+
194
+ # Re-create iterated data if `by` is assigned by users
195
+ data = (
196
+ create_iter_data_given_by(self.data, self._kind)
197
+ if self.by is not None
198
+ else self.data
199
+ )
200
+
201
+ # error: Argument "data" to "_iter_data" of "MPLPlot" has
202
+ # incompatible type "object"; expected "DataFrame |
203
+ # dict[Hashable, Series | DataFrame]"
204
+ for i, (label, y) in enumerate(self._iter_data(data=data)): # type: ignore[arg-type]
205
+ ax = self._get_ax(i)
206
+ kwds = self.kwds.copy()
207
+
208
+ # When by is applied, show title for subplots to know which group it is
209
+ # just like df.boxplot, and need to apply T on y to provide right input
210
+ if self.by is not None:
211
+ y = y.T
212
+ ax.set_title(pprint_thing(label))
213
+
214
+ # When `by` is assigned, the ticklabels will become unique grouped
215
+ # values, instead of label which is used as subtitle in this case.
216
+ # error: "Index" has no attribute "levels"; maybe "nlevels"?
217
+ levels = self.data.columns.levels # type: ignore[attr-defined]
218
+ ticklabels = [pprint_thing(col) for col in levels[0]]
219
+ else:
220
+ ticklabels = [pprint_thing(label)]
221
+
222
+ ret, bp = self._plot(
223
+ ax, y, column_num=i, return_type=self.return_type, **kwds
224
+ )
225
+ self.maybe_color_bp(bp)
226
+ self._return_obj[label] = ret
227
+ _set_ticklabels(
228
+ ax=ax, labels=ticklabels, is_vertical=self.orientation == "vertical"
229
+ )
230
+ else:
231
+ y = self.data.values.T
232
+ ax = self._get_ax(0)
233
+ kwds = self.kwds.copy()
234
+
235
+ ret, bp = self._plot(
236
+ ax, y, column_num=0, return_type=self.return_type, **kwds
237
+ )
238
+ self.maybe_color_bp(bp)
239
+ self._return_obj = ret
240
+
241
+ labels = [pprint_thing(left) for left in self.data.columns]
242
+ if not self.use_index:
243
+ labels = [pprint_thing(key) for key in range(len(labels))]
244
+ _set_ticklabels(
245
+ ax=ax, labels=labels, is_vertical=self.orientation == "vertical"
246
+ )
247
+
248
+ def _make_legend(self) -> None:
249
+ pass
250
+
251
+ def _post_plot_logic(self, ax: Axes, data) -> None:
252
+ # GH 45465: make sure that the boxplot doesn't ignore xlabel/ylabel
253
+ if self.xlabel:
254
+ ax.set_xlabel(pprint_thing(self.xlabel))
255
+ if self.ylabel:
256
+ ax.set_ylabel(pprint_thing(self.ylabel))
257
+
258
+ @property
259
+ def orientation(self) -> Literal["horizontal", "vertical"]:
260
+ if self.kwds.get("vert", True):
261
+ return "vertical"
262
+ else:
263
+ return "horizontal"
264
+
265
+ @property
266
+ def result(self):
267
+ if self.return_type is None:
268
+ return super().result
269
+ else:
270
+ return self._return_obj
271
+
272
+
273
+ def maybe_color_bp(bp, color_tup, **kwds) -> None:
274
+ # GH#30346, when users specifying those arguments explicitly, our defaults
275
+ # for these four kwargs should be overridden; if not, use Pandas settings
276
+ if not kwds.get("boxprops"):
277
+ setp(bp["boxes"], color=color_tup[0], alpha=1)
278
+ if not kwds.get("whiskerprops"):
279
+ setp(bp["whiskers"], color=color_tup[1], alpha=1)
280
+ if not kwds.get("medianprops"):
281
+ setp(bp["medians"], color=color_tup[2], alpha=1)
282
+ if not kwds.get("capprops"):
283
+ setp(bp["caps"], color=color_tup[3], alpha=1)
284
+
285
+
286
+ def _grouped_plot_by_column(
287
+ plotf,
288
+ data,
289
+ columns=None,
290
+ by=None,
291
+ numeric_only: bool = True,
292
+ grid: bool = False,
293
+ figsize: tuple[float, float] | None = None,
294
+ ax=None,
295
+ layout=None,
296
+ return_type=None,
297
+ **kwargs,
298
+ ):
299
+ grouped = data.groupby(by, observed=False)
300
+ if columns is None:
301
+ if not isinstance(by, (list, tuple)):
302
+ by = [by]
303
+ columns = data._get_numeric_data().columns.difference(by)
304
+ naxes = len(columns)
305
+ fig, axes = create_subplots(
306
+ naxes=naxes,
307
+ sharex=kwargs.pop("sharex", True),
308
+ sharey=kwargs.pop("sharey", True),
309
+ figsize=figsize,
310
+ ax=ax,
311
+ layout=layout,
312
+ )
313
+
314
+ _axes = flatten_axes(axes)
315
+
316
+ # GH 45465: move the "by" label based on "vert"
317
+ xlabel, ylabel = kwargs.pop("xlabel", None), kwargs.pop("ylabel", None)
318
+ if kwargs.get("vert", True):
319
+ xlabel = xlabel or by
320
+ else:
321
+ ylabel = ylabel or by
322
+
323
+ ax_values = []
324
+
325
+ for i, col in enumerate(columns):
326
+ ax = _axes[i]
327
+ gp_col = grouped[col]
328
+ keys, values = zip(*gp_col)
329
+ re_plotf = plotf(keys, values, ax, xlabel=xlabel, ylabel=ylabel, **kwargs)
330
+ ax.set_title(col)
331
+ ax_values.append(re_plotf)
332
+ ax.grid(grid)
333
+
334
+ result = pd.Series(ax_values, index=columns, copy=False)
335
+
336
+ # Return axes in multiplot case, maybe revisit later # 985
337
+ if return_type is None:
338
+ result = axes
339
+
340
+ byline = by[0] if len(by) == 1 else by
341
+ fig.suptitle(f"Boxplot grouped by {byline}")
342
+ maybe_adjust_figure(fig, bottom=0.15, top=0.9, left=0.1, right=0.9, wspace=0.2)
343
+
344
+ return result
345
+
346
+
347
+ def boxplot(
348
+ data,
349
+ column=None,
350
+ by=None,
351
+ ax=None,
352
+ fontsize: int | None = None,
353
+ rot: int = 0,
354
+ grid: bool = True,
355
+ figsize: tuple[float, float] | None = None,
356
+ layout=None,
357
+ return_type=None,
358
+ **kwds,
359
+ ):
360
+ import matplotlib.pyplot as plt
361
+
362
+ # validate return_type:
363
+ if return_type not in BoxPlot._valid_return_types:
364
+ raise ValueError("return_type must be {'axes', 'dict', 'both'}")
365
+
366
+ if isinstance(data, ABCSeries):
367
+ data = data.to_frame("x")
368
+ column = "x"
369
+
370
+ def _get_colors():
371
+ # num_colors=3 is required as method maybe_color_bp takes the colors
372
+ # in positions 0 and 2.
373
+ # if colors not provided, use same defaults as DataFrame.plot.box
374
+ result = get_standard_colors(num_colors=3)
375
+ result = np.take(result, [0, 0, 2])
376
+ result = np.append(result, "k")
377
+
378
+ colors = kwds.pop("color", None)
379
+ if colors:
380
+ if is_dict_like(colors):
381
+ # replace colors in result array with user-specified colors
382
+ # taken from the colors dict parameter
383
+ # "boxes" value placed in position 0, "whiskers" in 1, etc.
384
+ valid_keys = ["boxes", "whiskers", "medians", "caps"]
385
+ key_to_index = dict(zip(valid_keys, range(4)))
386
+ for key, value in colors.items():
387
+ if key in valid_keys:
388
+ result[key_to_index[key]] = value
389
+ else:
390
+ raise ValueError(
391
+ f"color dict contains invalid key '{key}'. "
392
+ f"The key must be either {valid_keys}"
393
+ )
394
+ else:
395
+ result.fill(colors)
396
+
397
+ return result
398
+
399
+ def plot_group(keys, values, ax: Axes, **kwds):
400
+ # GH 45465: xlabel/ylabel need to be popped out before plotting happens
401
+ xlabel, ylabel = kwds.pop("xlabel", None), kwds.pop("ylabel", None)
402
+ if xlabel:
403
+ ax.set_xlabel(pprint_thing(xlabel))
404
+ if ylabel:
405
+ ax.set_ylabel(pprint_thing(ylabel))
406
+
407
+ keys = [pprint_thing(x) for x in keys]
408
+ values = [np.asarray(remove_na_arraylike(v), dtype=object) for v in values]
409
+ bp = ax.boxplot(values, **kwds)
410
+ if fontsize is not None:
411
+ ax.tick_params(axis="both", labelsize=fontsize)
412
+
413
+ # GH 45465: x/y are flipped when "vert" changes
414
+ _set_ticklabels(
415
+ ax=ax, labels=keys, is_vertical=kwds.get("vert", True), rotation=rot
416
+ )
417
+ maybe_color_bp(bp, color_tup=colors, **kwds)
418
+
419
+ # Return axes in multiplot case, maybe revisit later # 985
420
+ if return_type == "dict":
421
+ return bp
422
+ elif return_type == "both":
423
+ return BoxPlot.BP(ax=ax, lines=bp)
424
+ else:
425
+ return ax
426
+
427
+ colors = _get_colors()
428
+ if column is None:
429
+ columns = None
430
+ elif isinstance(column, (list, tuple)):
431
+ columns = column
432
+ else:
433
+ columns = [column]
434
+
435
+ if by is not None:
436
+ # Prefer array return type for 2-D plots to match the subplot layout
437
+ # https://github.com/pandas-dev/pandas/pull/12216#issuecomment-241175580
438
+ result = _grouped_plot_by_column(
439
+ plot_group,
440
+ data,
441
+ columns=columns,
442
+ by=by,
443
+ grid=grid,
444
+ figsize=figsize,
445
+ ax=ax,
446
+ layout=layout,
447
+ return_type=return_type,
448
+ **kwds,
449
+ )
450
+ else:
451
+ if return_type is None:
452
+ return_type = "axes"
453
+ if layout is not None:
454
+ raise ValueError("The 'layout' keyword is not supported when 'by' is None")
455
+
456
+ if ax is None:
457
+ rc = {"figure.figsize": figsize} if figsize is not None else {}
458
+ with plt.rc_context(rc):
459
+ ax = plt.gca()
460
+ data = data._get_numeric_data()
461
+ naxes = len(data.columns)
462
+ if naxes == 0:
463
+ raise ValueError(
464
+ "boxplot method requires numerical columns, nothing to plot."
465
+ )
466
+ if columns is None:
467
+ columns = data.columns
468
+ else:
469
+ data = data[columns]
470
+
471
+ result = plot_group(columns, data.values.T, ax, **kwds)
472
+ ax.grid(grid)
473
+
474
+ return result
475
+
476
+
477
+ def boxplot_frame(
478
+ self,
479
+ column=None,
480
+ by=None,
481
+ ax=None,
482
+ fontsize: int | None = None,
483
+ rot: int = 0,
484
+ grid: bool = True,
485
+ figsize: tuple[float, float] | None = None,
486
+ layout=None,
487
+ return_type=None,
488
+ **kwds,
489
+ ):
490
+ import matplotlib.pyplot as plt
491
+
492
+ ax = boxplot(
493
+ self,
494
+ column=column,
495
+ by=by,
496
+ ax=ax,
497
+ fontsize=fontsize,
498
+ grid=grid,
499
+ rot=rot,
500
+ figsize=figsize,
501
+ layout=layout,
502
+ return_type=return_type,
503
+ **kwds,
504
+ )
505
+ plt.draw_if_interactive()
506
+ return ax
507
+
508
+
509
+ def boxplot_frame_groupby(
510
+ grouped,
511
+ subplots: bool = True,
512
+ column=None,
513
+ fontsize: int | None = None,
514
+ rot: int = 0,
515
+ grid: bool = True,
516
+ ax=None,
517
+ figsize: tuple[float, float] | None = None,
518
+ layout=None,
519
+ sharex: bool = False,
520
+ sharey: bool = True,
521
+ **kwds,
522
+ ):
523
+ if subplots is True:
524
+ naxes = len(grouped)
525
+ fig, axes = create_subplots(
526
+ naxes=naxes,
527
+ squeeze=False,
528
+ ax=ax,
529
+ sharex=sharex,
530
+ sharey=sharey,
531
+ figsize=figsize,
532
+ layout=layout,
533
+ )
534
+ axes = flatten_axes(axes)
535
+
536
+ ret = pd.Series(dtype=object)
537
+
538
+ for (key, group), ax in zip(grouped, axes):
539
+ d = group.boxplot(
540
+ ax=ax, column=column, fontsize=fontsize, rot=rot, grid=grid, **kwds
541
+ )
542
+ ax.set_title(pprint_thing(key))
543
+ ret.loc[key] = d
544
+ maybe_adjust_figure(fig, bottom=0.15, top=0.9, left=0.1, right=0.9, wspace=0.2)
545
+ else:
546
+ keys, frames = zip(*grouped)
547
+ if grouped.axis == 0:
548
+ df = pd.concat(frames, keys=keys, axis=1)
549
+ elif len(frames) > 1:
550
+ df = frames[0].join(frames[1::])
551
+ else:
552
+ df = frames[0]
553
+
554
+ # GH 16748, DataFrameGroupby fails when subplots=False and `column` argument
555
+ # is assigned, and in this case, since `df` here becomes MI after groupby,
556
+ # so we need to couple the keys (grouped values) and column (original df
557
+ # column) together to search for subset to plot
558
+ if column is not None:
559
+ column = com.convert_to_list_like(column)
560
+ multi_key = pd.MultiIndex.from_product([keys, column])
561
+ column = list(multi_key.values)
562
+ ret = df.boxplot(
563
+ column=column,
564
+ fontsize=fontsize,
565
+ rot=rot,
566
+ grid=grid,
567
+ ax=ax,
568
+ figsize=figsize,
569
+ layout=layout,
570
+ **kwds,
571
+ )
572
+ return ret
venv/lib/python3.10/site-packages/pandas/plotting/_matplotlib/converter.py ADDED
@@ -0,0 +1,1135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import contextlib
4
+ import datetime as pydt
5
+ from datetime import (
6
+ datetime,
7
+ timedelta,
8
+ tzinfo,
9
+ )
10
+ import functools
11
+ from typing import (
12
+ TYPE_CHECKING,
13
+ Any,
14
+ cast,
15
+ )
16
+ import warnings
17
+
18
+ import matplotlib.dates as mdates
19
+ from matplotlib.ticker import (
20
+ AutoLocator,
21
+ Formatter,
22
+ Locator,
23
+ )
24
+ from matplotlib.transforms import nonsingular
25
+ import matplotlib.units as munits
26
+ import numpy as np
27
+
28
+ from pandas._libs import lib
29
+ from pandas._libs.tslibs import (
30
+ Timestamp,
31
+ to_offset,
32
+ )
33
+ from pandas._libs.tslibs.dtypes import (
34
+ FreqGroup,
35
+ periods_per_day,
36
+ )
37
+ from pandas._typing import (
38
+ F,
39
+ npt,
40
+ )
41
+
42
+ from pandas.core.dtypes.common import (
43
+ is_float,
44
+ is_float_dtype,
45
+ is_integer,
46
+ is_integer_dtype,
47
+ is_nested_list_like,
48
+ )
49
+
50
+ from pandas import (
51
+ Index,
52
+ Series,
53
+ get_option,
54
+ )
55
+ import pandas.core.common as com
56
+ from pandas.core.indexes.datetimes import date_range
57
+ from pandas.core.indexes.period import (
58
+ Period,
59
+ PeriodIndex,
60
+ period_range,
61
+ )
62
+ import pandas.core.tools.datetimes as tools
63
+
64
+ if TYPE_CHECKING:
65
+ from collections.abc import Generator
66
+
67
+ from matplotlib.axis import Axis
68
+
69
+ from pandas._libs.tslibs.offsets import BaseOffset
70
+
71
+
72
+ _mpl_units = {} # Cache for units overwritten by us
73
+
74
+
75
+ def get_pairs():
76
+ pairs = [
77
+ (Timestamp, DatetimeConverter),
78
+ (Period, PeriodConverter),
79
+ (pydt.datetime, DatetimeConverter),
80
+ (pydt.date, DatetimeConverter),
81
+ (pydt.time, TimeConverter),
82
+ (np.datetime64, DatetimeConverter),
83
+ ]
84
+ return pairs
85
+
86
+
87
+ def register_pandas_matplotlib_converters(func: F) -> F:
88
+ """
89
+ Decorator applying pandas_converters.
90
+ """
91
+
92
+ @functools.wraps(func)
93
+ def wrapper(*args, **kwargs):
94
+ with pandas_converters():
95
+ return func(*args, **kwargs)
96
+
97
+ return cast(F, wrapper)
98
+
99
+
100
+ @contextlib.contextmanager
101
+ def pandas_converters() -> Generator[None, None, None]:
102
+ """
103
+ Context manager registering pandas' converters for a plot.
104
+
105
+ See Also
106
+ --------
107
+ register_pandas_matplotlib_converters : Decorator that applies this.
108
+ """
109
+ value = get_option("plotting.matplotlib.register_converters")
110
+
111
+ if value:
112
+ # register for True or "auto"
113
+ register()
114
+ try:
115
+ yield
116
+ finally:
117
+ if value == "auto":
118
+ # only deregister for "auto"
119
+ deregister()
120
+
121
+
122
+ def register() -> None:
123
+ pairs = get_pairs()
124
+ for type_, cls in pairs:
125
+ # Cache previous converter if present
126
+ if type_ in munits.registry and not isinstance(munits.registry[type_], cls):
127
+ previous = munits.registry[type_]
128
+ _mpl_units[type_] = previous
129
+ # Replace with pandas converter
130
+ munits.registry[type_] = cls()
131
+
132
+
133
+ def deregister() -> None:
134
+ # Renamed in pandas.plotting.__init__
135
+ for type_, cls in get_pairs():
136
+ # We use type to catch our classes directly, no inheritance
137
+ if type(munits.registry.get(type_)) is cls:
138
+ munits.registry.pop(type_)
139
+
140
+ # restore the old keys
141
+ for unit, formatter in _mpl_units.items():
142
+ if type(formatter) not in {DatetimeConverter, PeriodConverter, TimeConverter}:
143
+ # make it idempotent by excluding ours.
144
+ munits.registry[unit] = formatter
145
+
146
+
147
+ def _to_ordinalf(tm: pydt.time) -> float:
148
+ tot_sec = tm.hour * 3600 + tm.minute * 60 + tm.second + tm.microsecond / 10**6
149
+ return tot_sec
150
+
151
+
152
+ def time2num(d):
153
+ if isinstance(d, str):
154
+ parsed = Timestamp(d)
155
+ return _to_ordinalf(parsed.time())
156
+ if isinstance(d, pydt.time):
157
+ return _to_ordinalf(d)
158
+ return d
159
+
160
+
161
+ class TimeConverter(munits.ConversionInterface):
162
+ @staticmethod
163
+ def convert(value, unit, axis):
164
+ valid_types = (str, pydt.time)
165
+ if isinstance(value, valid_types) or is_integer(value) or is_float(value):
166
+ return time2num(value)
167
+ if isinstance(value, Index):
168
+ return value.map(time2num)
169
+ if isinstance(value, (list, tuple, np.ndarray, Index)):
170
+ return [time2num(x) for x in value]
171
+ return value
172
+
173
+ @staticmethod
174
+ def axisinfo(unit, axis) -> munits.AxisInfo | None:
175
+ if unit != "time":
176
+ return None
177
+
178
+ majloc = AutoLocator()
179
+ majfmt = TimeFormatter(majloc)
180
+ return munits.AxisInfo(majloc=majloc, majfmt=majfmt, label="time")
181
+
182
+ @staticmethod
183
+ def default_units(x, axis) -> str:
184
+ return "time"
185
+
186
+
187
+ # time formatter
188
+ class TimeFormatter(Formatter):
189
+ def __init__(self, locs) -> None:
190
+ self.locs = locs
191
+
192
+ def __call__(self, x, pos: int | None = 0) -> str:
193
+ """
194
+ Return the time of day as a formatted string.
195
+
196
+ Parameters
197
+ ----------
198
+ x : float
199
+ The time of day specified as seconds since 00:00 (midnight),
200
+ with up to microsecond precision.
201
+ pos
202
+ Unused
203
+
204
+ Returns
205
+ -------
206
+ str
207
+ A string in HH:MM:SS.mmmuuu format. Microseconds,
208
+ milliseconds and seconds are only displayed if non-zero.
209
+ """
210
+ fmt = "%H:%M:%S.%f"
211
+ s = int(x)
212
+ msus = round((x - s) * 10**6)
213
+ ms = msus // 1000
214
+ us = msus % 1000
215
+ m, s = divmod(s, 60)
216
+ h, m = divmod(m, 60)
217
+ _, h = divmod(h, 24)
218
+ if us != 0:
219
+ return pydt.time(h, m, s, msus).strftime(fmt)
220
+ elif ms != 0:
221
+ return pydt.time(h, m, s, msus).strftime(fmt)[:-3]
222
+ elif s != 0:
223
+ return pydt.time(h, m, s).strftime("%H:%M:%S")
224
+
225
+ return pydt.time(h, m).strftime("%H:%M")
226
+
227
+
228
+ # Period Conversion
229
+
230
+
231
+ class PeriodConverter(mdates.DateConverter):
232
+ @staticmethod
233
+ def convert(values, units, axis):
234
+ if is_nested_list_like(values):
235
+ values = [PeriodConverter._convert_1d(v, units, axis) for v in values]
236
+ else:
237
+ values = PeriodConverter._convert_1d(values, units, axis)
238
+ return values
239
+
240
+ @staticmethod
241
+ def _convert_1d(values, units, axis):
242
+ if not hasattr(axis, "freq"):
243
+ raise TypeError("Axis must have `freq` set to convert to Periods")
244
+ valid_types = (str, datetime, Period, pydt.date, pydt.time, np.datetime64)
245
+ with warnings.catch_warnings():
246
+ warnings.filterwarnings(
247
+ "ignore", "Period with BDay freq is deprecated", category=FutureWarning
248
+ )
249
+ warnings.filterwarnings(
250
+ "ignore", r"PeriodDtype\[B\] is deprecated", category=FutureWarning
251
+ )
252
+ if (
253
+ isinstance(values, valid_types)
254
+ or is_integer(values)
255
+ or is_float(values)
256
+ ):
257
+ return get_datevalue(values, axis.freq)
258
+ elif isinstance(values, PeriodIndex):
259
+ return values.asfreq(axis.freq).asi8
260
+ elif isinstance(values, Index):
261
+ return values.map(lambda x: get_datevalue(x, axis.freq))
262
+ elif lib.infer_dtype(values, skipna=False) == "period":
263
+ # https://github.com/pandas-dev/pandas/issues/24304
264
+ # convert ndarray[period] -> PeriodIndex
265
+ return PeriodIndex(values, freq=axis.freq).asi8
266
+ elif isinstance(values, (list, tuple, np.ndarray, Index)):
267
+ return [get_datevalue(x, axis.freq) for x in values]
268
+ return values
269
+
270
+
271
+ def get_datevalue(date, freq):
272
+ if isinstance(date, Period):
273
+ return date.asfreq(freq).ordinal
274
+ elif isinstance(date, (str, datetime, pydt.date, pydt.time, np.datetime64)):
275
+ return Period(date, freq).ordinal
276
+ elif (
277
+ is_integer(date)
278
+ or is_float(date)
279
+ or (isinstance(date, (np.ndarray, Index)) and (date.size == 1))
280
+ ):
281
+ return date
282
+ elif date is None:
283
+ return None
284
+ raise ValueError(f"Unrecognizable date '{date}'")
285
+
286
+
287
+ # Datetime Conversion
288
+ class DatetimeConverter(mdates.DateConverter):
289
+ @staticmethod
290
+ def convert(values, unit, axis):
291
+ # values might be a 1-d array, or a list-like of arrays.
292
+ if is_nested_list_like(values):
293
+ values = [DatetimeConverter._convert_1d(v, unit, axis) for v in values]
294
+ else:
295
+ values = DatetimeConverter._convert_1d(values, unit, axis)
296
+ return values
297
+
298
+ @staticmethod
299
+ def _convert_1d(values, unit, axis):
300
+ def try_parse(values):
301
+ try:
302
+ return mdates.date2num(tools.to_datetime(values))
303
+ except Exception:
304
+ return values
305
+
306
+ if isinstance(values, (datetime, pydt.date, np.datetime64, pydt.time)):
307
+ return mdates.date2num(values)
308
+ elif is_integer(values) or is_float(values):
309
+ return values
310
+ elif isinstance(values, str):
311
+ return try_parse(values)
312
+ elif isinstance(values, (list, tuple, np.ndarray, Index, Series)):
313
+ if isinstance(values, Series):
314
+ # https://github.com/matplotlib/matplotlib/issues/11391
315
+ # Series was skipped. Convert to DatetimeIndex to get asi8
316
+ values = Index(values)
317
+ if isinstance(values, Index):
318
+ values = values.values
319
+ if not isinstance(values, np.ndarray):
320
+ values = com.asarray_tuplesafe(values)
321
+
322
+ if is_integer_dtype(values) or is_float_dtype(values):
323
+ return values
324
+
325
+ try:
326
+ values = tools.to_datetime(values)
327
+ except Exception:
328
+ pass
329
+
330
+ values = mdates.date2num(values)
331
+
332
+ return values
333
+
334
+ @staticmethod
335
+ def axisinfo(unit: tzinfo | None, axis) -> munits.AxisInfo:
336
+ """
337
+ Return the :class:`~matplotlib.units.AxisInfo` for *unit*.
338
+
339
+ *unit* is a tzinfo instance or None.
340
+ The *axis* argument is required but not used.
341
+ """
342
+ tz = unit
343
+
344
+ majloc = PandasAutoDateLocator(tz=tz)
345
+ majfmt = PandasAutoDateFormatter(majloc, tz=tz)
346
+ datemin = pydt.date(2000, 1, 1)
347
+ datemax = pydt.date(2010, 1, 1)
348
+
349
+ return munits.AxisInfo(
350
+ majloc=majloc, majfmt=majfmt, label="", default_limits=(datemin, datemax)
351
+ )
352
+
353
+
354
+ class PandasAutoDateFormatter(mdates.AutoDateFormatter):
355
+ def __init__(self, locator, tz=None, defaultfmt: str = "%Y-%m-%d") -> None:
356
+ mdates.AutoDateFormatter.__init__(self, locator, tz, defaultfmt)
357
+
358
+
359
+ class PandasAutoDateLocator(mdates.AutoDateLocator):
360
+ def get_locator(self, dmin, dmax):
361
+ """Pick the best locator based on a distance."""
362
+ tot_sec = (dmax - dmin).total_seconds()
363
+
364
+ if abs(tot_sec) < self.minticks:
365
+ self._freq = -1
366
+ locator = MilliSecondLocator(self.tz)
367
+ locator.set_axis(self.axis)
368
+
369
+ # error: Item "None" of "Axis | _DummyAxis | _AxisWrapper | None"
370
+ # has no attribute "get_data_interval"
371
+ locator.axis.set_view_interval( # type: ignore[union-attr]
372
+ *self.axis.get_view_interval() # type: ignore[union-attr]
373
+ )
374
+ locator.axis.set_data_interval( # type: ignore[union-attr]
375
+ *self.axis.get_data_interval() # type: ignore[union-attr]
376
+ )
377
+ return locator
378
+
379
+ return mdates.AutoDateLocator.get_locator(self, dmin, dmax)
380
+
381
+ def _get_unit(self):
382
+ return MilliSecondLocator.get_unit_generic(self._freq)
383
+
384
+
385
+ class MilliSecondLocator(mdates.DateLocator):
386
+ UNIT = 1.0 / (24 * 3600 * 1000)
387
+
388
+ def __init__(self, tz) -> None:
389
+ mdates.DateLocator.__init__(self, tz)
390
+ self._interval = 1.0
391
+
392
+ def _get_unit(self):
393
+ return self.get_unit_generic(-1)
394
+
395
+ @staticmethod
396
+ def get_unit_generic(freq):
397
+ unit = mdates.RRuleLocator.get_unit_generic(freq)
398
+ if unit < 0:
399
+ return MilliSecondLocator.UNIT
400
+ return unit
401
+
402
+ def __call__(self):
403
+ # if no data have been set, this will tank with a ValueError
404
+ try:
405
+ dmin, dmax = self.viewlim_to_dt()
406
+ except ValueError:
407
+ return []
408
+
409
+ # We need to cap at the endpoints of valid datetime
410
+ nmax, nmin = mdates.date2num((dmax, dmin))
411
+
412
+ num = (nmax - nmin) * 86400 * 1000
413
+ max_millis_ticks = 6
414
+ for interval in [1, 10, 50, 100, 200, 500]:
415
+ if num <= interval * (max_millis_ticks - 1):
416
+ self._interval = interval
417
+ break
418
+ # We went through the whole loop without breaking, default to 1
419
+ self._interval = 1000.0
420
+
421
+ estimate = (nmax - nmin) / (self._get_unit() * self._get_interval())
422
+
423
+ if estimate > self.MAXTICKS * 2:
424
+ raise RuntimeError(
425
+ "MillisecondLocator estimated to generate "
426
+ f"{estimate:d} ticks from {dmin} to {dmax}: exceeds Locator.MAXTICKS"
427
+ f"* 2 ({self.MAXTICKS * 2:d}) "
428
+ )
429
+
430
+ interval = self._get_interval()
431
+ freq = f"{interval}ms"
432
+ tz = self.tz.tzname(None)
433
+ st = dmin.replace(tzinfo=None)
434
+ ed = dmin.replace(tzinfo=None)
435
+ all_dates = date_range(start=st, end=ed, freq=freq, tz=tz).astype(object)
436
+
437
+ try:
438
+ if len(all_dates) > 0:
439
+ locs = self.raise_if_exceeds(mdates.date2num(all_dates))
440
+ return locs
441
+ except Exception: # pragma: no cover
442
+ pass
443
+
444
+ lims = mdates.date2num([dmin, dmax])
445
+ return lims
446
+
447
+ def _get_interval(self):
448
+ return self._interval
449
+
450
+ def autoscale(self):
451
+ """
452
+ Set the view limits to include the data range.
453
+ """
454
+ # We need to cap at the endpoints of valid datetime
455
+ dmin, dmax = self.datalim_to_dt()
456
+
457
+ vmin = mdates.date2num(dmin)
458
+ vmax = mdates.date2num(dmax)
459
+
460
+ return self.nonsingular(vmin, vmax)
461
+
462
+
463
+ def _from_ordinal(x, tz: tzinfo | None = None) -> datetime:
464
+ ix = int(x)
465
+ dt = datetime.fromordinal(ix)
466
+ remainder = float(x) - ix
467
+ hour, remainder = divmod(24 * remainder, 1)
468
+ minute, remainder = divmod(60 * remainder, 1)
469
+ second, remainder = divmod(60 * remainder, 1)
470
+ microsecond = int(1_000_000 * remainder)
471
+ if microsecond < 10:
472
+ microsecond = 0 # compensate for rounding errors
473
+ dt = datetime(
474
+ dt.year, dt.month, dt.day, int(hour), int(minute), int(second), microsecond
475
+ )
476
+ if tz is not None:
477
+ dt = dt.astimezone(tz)
478
+
479
+ if microsecond > 999990: # compensate for rounding errors
480
+ dt += timedelta(microseconds=1_000_000 - microsecond)
481
+
482
+ return dt
483
+
484
+
485
+ # Fixed frequency dynamic tick locators and formatters
486
+
487
+ # -------------------------------------------------------------------------
488
+ # --- Locators ---
489
+ # -------------------------------------------------------------------------
490
+
491
+
492
+ def _get_default_annual_spacing(nyears) -> tuple[int, int]:
493
+ """
494
+ Returns a default spacing between consecutive ticks for annual data.
495
+ """
496
+ if nyears < 11:
497
+ (min_spacing, maj_spacing) = (1, 1)
498
+ elif nyears < 20:
499
+ (min_spacing, maj_spacing) = (1, 2)
500
+ elif nyears < 50:
501
+ (min_spacing, maj_spacing) = (1, 5)
502
+ elif nyears < 100:
503
+ (min_spacing, maj_spacing) = (5, 10)
504
+ elif nyears < 200:
505
+ (min_spacing, maj_spacing) = (5, 25)
506
+ elif nyears < 600:
507
+ (min_spacing, maj_spacing) = (10, 50)
508
+ else:
509
+ factor = nyears // 1000 + 1
510
+ (min_spacing, maj_spacing) = (factor * 20, factor * 100)
511
+ return (min_spacing, maj_spacing)
512
+
513
+
514
+ def _period_break(dates: PeriodIndex, period: str) -> npt.NDArray[np.intp]:
515
+ """
516
+ Returns the indices where the given period changes.
517
+
518
+ Parameters
519
+ ----------
520
+ dates : PeriodIndex
521
+ Array of intervals to monitor.
522
+ period : str
523
+ Name of the period to monitor.
524
+ """
525
+ mask = _period_break_mask(dates, period)
526
+ return np.nonzero(mask)[0]
527
+
528
+
529
+ def _period_break_mask(dates: PeriodIndex, period: str) -> npt.NDArray[np.bool_]:
530
+ current = getattr(dates, period)
531
+ previous = getattr(dates - 1 * dates.freq, period)
532
+ return current != previous
533
+
534
+
535
+ def has_level_label(label_flags: npt.NDArray[np.intp], vmin: float) -> bool:
536
+ """
537
+ Returns true if the ``label_flags`` indicate there is at least one label
538
+ for this level.
539
+
540
+ if the minimum view limit is not an exact integer, then the first tick
541
+ label won't be shown, so we must adjust for that.
542
+ """
543
+ if label_flags.size == 0 or (
544
+ label_flags.size == 1 and label_flags[0] == 0 and vmin % 1 > 0.0
545
+ ):
546
+ return False
547
+ else:
548
+ return True
549
+
550
+
551
+ def _get_periods_per_ymd(freq: BaseOffset) -> tuple[int, int, int]:
552
+ # error: "BaseOffset" has no attribute "_period_dtype_code"
553
+ dtype_code = freq._period_dtype_code # type: ignore[attr-defined]
554
+ freq_group = FreqGroup.from_period_dtype_code(dtype_code)
555
+
556
+ ppd = -1 # placeholder for above-day freqs
557
+
558
+ if dtype_code >= FreqGroup.FR_HR.value:
559
+ # error: "BaseOffset" has no attribute "_creso"
560
+ ppd = periods_per_day(freq._creso) # type: ignore[attr-defined]
561
+ ppm = 28 * ppd
562
+ ppy = 365 * ppd
563
+ elif freq_group == FreqGroup.FR_BUS:
564
+ ppm = 19
565
+ ppy = 261
566
+ elif freq_group == FreqGroup.FR_DAY:
567
+ ppm = 28
568
+ ppy = 365
569
+ elif freq_group == FreqGroup.FR_WK:
570
+ ppm = 3
571
+ ppy = 52
572
+ elif freq_group == FreqGroup.FR_MTH:
573
+ ppm = 1
574
+ ppy = 12
575
+ elif freq_group == FreqGroup.FR_QTR:
576
+ ppm = -1 # placerholder
577
+ ppy = 4
578
+ elif freq_group == FreqGroup.FR_ANN:
579
+ ppm = -1 # placeholder
580
+ ppy = 1
581
+ else:
582
+ raise NotImplementedError(f"Unsupported frequency: {dtype_code}")
583
+
584
+ return ppd, ppm, ppy
585
+
586
+
587
+ def _daily_finder(vmin, vmax, freq: BaseOffset) -> np.ndarray:
588
+ # error: "BaseOffset" has no attribute "_period_dtype_code"
589
+ dtype_code = freq._period_dtype_code # type: ignore[attr-defined]
590
+
591
+ periodsperday, periodspermonth, periodsperyear = _get_periods_per_ymd(freq)
592
+
593
+ # save this for later usage
594
+ vmin_orig = vmin
595
+ (vmin, vmax) = (int(vmin), int(vmax))
596
+ span = vmax - vmin + 1
597
+
598
+ with warnings.catch_warnings():
599
+ warnings.filterwarnings(
600
+ "ignore", "Period with BDay freq is deprecated", category=FutureWarning
601
+ )
602
+ warnings.filterwarnings(
603
+ "ignore", r"PeriodDtype\[B\] is deprecated", category=FutureWarning
604
+ )
605
+ dates_ = period_range(
606
+ start=Period(ordinal=vmin, freq=freq),
607
+ end=Period(ordinal=vmax, freq=freq),
608
+ freq=freq,
609
+ )
610
+
611
+ # Initialize the output
612
+ info = np.zeros(
613
+ span, dtype=[("val", np.int64), ("maj", bool), ("min", bool), ("fmt", "|S20")]
614
+ )
615
+ info["val"][:] = dates_.asi8
616
+ info["fmt"][:] = ""
617
+ info["maj"][[0, -1]] = True
618
+ # .. and set some shortcuts
619
+ info_maj = info["maj"]
620
+ info_min = info["min"]
621
+ info_fmt = info["fmt"]
622
+
623
+ def first_label(label_flags):
624
+ if (label_flags[0] == 0) and (label_flags.size > 1) and ((vmin_orig % 1) > 0.0):
625
+ return label_flags[1]
626
+ else:
627
+ return label_flags[0]
628
+
629
+ # Case 1. Less than a month
630
+ if span <= periodspermonth:
631
+ day_start = _period_break(dates_, "day")
632
+ month_start = _period_break(dates_, "month")
633
+ year_start = _period_break(dates_, "year")
634
+
635
+ def _hour_finder(label_interval: int, force_year_start: bool) -> None:
636
+ target = dates_.hour
637
+ mask = _period_break_mask(dates_, "hour")
638
+ info_maj[day_start] = True
639
+ info_min[mask & (target % label_interval == 0)] = True
640
+ info_fmt[mask & (target % label_interval == 0)] = "%H:%M"
641
+ info_fmt[day_start] = "%H:%M\n%d-%b"
642
+ info_fmt[year_start] = "%H:%M\n%d-%b\n%Y"
643
+ if force_year_start and not has_level_label(year_start, vmin_orig):
644
+ info_fmt[first_label(day_start)] = "%H:%M\n%d-%b\n%Y"
645
+
646
+ def _minute_finder(label_interval: int) -> None:
647
+ target = dates_.minute
648
+ hour_start = _period_break(dates_, "hour")
649
+ mask = _period_break_mask(dates_, "minute")
650
+ info_maj[hour_start] = True
651
+ info_min[mask & (target % label_interval == 0)] = True
652
+ info_fmt[mask & (target % label_interval == 0)] = "%H:%M"
653
+ info_fmt[day_start] = "%H:%M\n%d-%b"
654
+ info_fmt[year_start] = "%H:%M\n%d-%b\n%Y"
655
+
656
+ def _second_finder(label_interval: int) -> None:
657
+ target = dates_.second
658
+ minute_start = _period_break(dates_, "minute")
659
+ mask = _period_break_mask(dates_, "second")
660
+ info_maj[minute_start] = True
661
+ info_min[mask & (target % label_interval == 0)] = True
662
+ info_fmt[mask & (target % label_interval == 0)] = "%H:%M:%S"
663
+ info_fmt[day_start] = "%H:%M:%S\n%d-%b"
664
+ info_fmt[year_start] = "%H:%M:%S\n%d-%b\n%Y"
665
+
666
+ if span < periodsperday / 12000:
667
+ _second_finder(1)
668
+ elif span < periodsperday / 6000:
669
+ _second_finder(2)
670
+ elif span < periodsperday / 2400:
671
+ _second_finder(5)
672
+ elif span < periodsperday / 1200:
673
+ _second_finder(10)
674
+ elif span < periodsperday / 800:
675
+ _second_finder(15)
676
+ elif span < periodsperday / 400:
677
+ _second_finder(30)
678
+ elif span < periodsperday / 150:
679
+ _minute_finder(1)
680
+ elif span < periodsperday / 70:
681
+ _minute_finder(2)
682
+ elif span < periodsperday / 24:
683
+ _minute_finder(5)
684
+ elif span < periodsperday / 12:
685
+ _minute_finder(15)
686
+ elif span < periodsperday / 6:
687
+ _minute_finder(30)
688
+ elif span < periodsperday / 2.5:
689
+ _hour_finder(1, False)
690
+ elif span < periodsperday / 1.5:
691
+ _hour_finder(2, False)
692
+ elif span < periodsperday * 1.25:
693
+ _hour_finder(3, False)
694
+ elif span < periodsperday * 2.5:
695
+ _hour_finder(6, True)
696
+ elif span < periodsperday * 4:
697
+ _hour_finder(12, True)
698
+ else:
699
+ info_maj[month_start] = True
700
+ info_min[day_start] = True
701
+ info_fmt[day_start] = "%d"
702
+ info_fmt[month_start] = "%d\n%b"
703
+ info_fmt[year_start] = "%d\n%b\n%Y"
704
+ if not has_level_label(year_start, vmin_orig):
705
+ if not has_level_label(month_start, vmin_orig):
706
+ info_fmt[first_label(day_start)] = "%d\n%b\n%Y"
707
+ else:
708
+ info_fmt[first_label(month_start)] = "%d\n%b\n%Y"
709
+
710
+ # Case 2. Less than three months
711
+ elif span <= periodsperyear // 4:
712
+ month_start = _period_break(dates_, "month")
713
+ info_maj[month_start] = True
714
+ if dtype_code < FreqGroup.FR_HR.value:
715
+ info["min"] = True
716
+ else:
717
+ day_start = _period_break(dates_, "day")
718
+ info["min"][day_start] = True
719
+ week_start = _period_break(dates_, "week")
720
+ year_start = _period_break(dates_, "year")
721
+ info_fmt[week_start] = "%d"
722
+ info_fmt[month_start] = "\n\n%b"
723
+ info_fmt[year_start] = "\n\n%b\n%Y"
724
+ if not has_level_label(year_start, vmin_orig):
725
+ if not has_level_label(month_start, vmin_orig):
726
+ info_fmt[first_label(week_start)] = "\n\n%b\n%Y"
727
+ else:
728
+ info_fmt[first_label(month_start)] = "\n\n%b\n%Y"
729
+ # Case 3. Less than 14 months ...............
730
+ elif span <= 1.15 * periodsperyear:
731
+ year_start = _period_break(dates_, "year")
732
+ month_start = _period_break(dates_, "month")
733
+ week_start = _period_break(dates_, "week")
734
+ info_maj[month_start] = True
735
+ info_min[week_start] = True
736
+ info_min[year_start] = False
737
+ info_min[month_start] = False
738
+ info_fmt[month_start] = "%b"
739
+ info_fmt[year_start] = "%b\n%Y"
740
+ if not has_level_label(year_start, vmin_orig):
741
+ info_fmt[first_label(month_start)] = "%b\n%Y"
742
+ # Case 4. Less than 2.5 years ...............
743
+ elif span <= 2.5 * periodsperyear:
744
+ year_start = _period_break(dates_, "year")
745
+ quarter_start = _period_break(dates_, "quarter")
746
+ month_start = _period_break(dates_, "month")
747
+ info_maj[quarter_start] = True
748
+ info_min[month_start] = True
749
+ info_fmt[quarter_start] = "%b"
750
+ info_fmt[year_start] = "%b\n%Y"
751
+ # Case 4. Less than 4 years .................
752
+ elif span <= 4 * periodsperyear:
753
+ year_start = _period_break(dates_, "year")
754
+ month_start = _period_break(dates_, "month")
755
+ info_maj[year_start] = True
756
+ info_min[month_start] = True
757
+ info_min[year_start] = False
758
+
759
+ month_break = dates_[month_start].month
760
+ jan_or_jul = month_start[(month_break == 1) | (month_break == 7)]
761
+ info_fmt[jan_or_jul] = "%b"
762
+ info_fmt[year_start] = "%b\n%Y"
763
+ # Case 5. Less than 11 years ................
764
+ elif span <= 11 * periodsperyear:
765
+ year_start = _period_break(dates_, "year")
766
+ quarter_start = _period_break(dates_, "quarter")
767
+ info_maj[year_start] = True
768
+ info_min[quarter_start] = True
769
+ info_min[year_start] = False
770
+ info_fmt[year_start] = "%Y"
771
+ # Case 6. More than 12 years ................
772
+ else:
773
+ year_start = _period_break(dates_, "year")
774
+ year_break = dates_[year_start].year
775
+ nyears = span / periodsperyear
776
+ (min_anndef, maj_anndef) = _get_default_annual_spacing(nyears)
777
+ major_idx = year_start[(year_break % maj_anndef == 0)]
778
+ info_maj[major_idx] = True
779
+ minor_idx = year_start[(year_break % min_anndef == 0)]
780
+ info_min[minor_idx] = True
781
+ info_fmt[major_idx] = "%Y"
782
+
783
+ return info
784
+
785
+
786
+ def _monthly_finder(vmin, vmax, freq: BaseOffset) -> np.ndarray:
787
+ _, _, periodsperyear = _get_periods_per_ymd(freq)
788
+
789
+ vmin_orig = vmin
790
+ (vmin, vmax) = (int(vmin), int(vmax))
791
+ span = vmax - vmin + 1
792
+
793
+ # Initialize the output
794
+ info = np.zeros(
795
+ span, dtype=[("val", int), ("maj", bool), ("min", bool), ("fmt", "|S8")]
796
+ )
797
+ info["val"] = np.arange(vmin, vmax + 1)
798
+ dates_ = info["val"]
799
+ info["fmt"] = ""
800
+ year_start = (dates_ % 12 == 0).nonzero()[0]
801
+ info_maj = info["maj"]
802
+ info_fmt = info["fmt"]
803
+
804
+ if span <= 1.15 * periodsperyear:
805
+ info_maj[year_start] = True
806
+ info["min"] = True
807
+
808
+ info_fmt[:] = "%b"
809
+ info_fmt[year_start] = "%b\n%Y"
810
+
811
+ if not has_level_label(year_start, vmin_orig):
812
+ if dates_.size > 1:
813
+ idx = 1
814
+ else:
815
+ idx = 0
816
+ info_fmt[idx] = "%b\n%Y"
817
+
818
+ elif span <= 2.5 * periodsperyear:
819
+ quarter_start = (dates_ % 3 == 0).nonzero()
820
+ info_maj[year_start] = True
821
+ # TODO: Check the following : is it really info['fmt'] ?
822
+ # 2023-09-15 this is reached in test_finder_monthly
823
+ info["fmt"][quarter_start] = True
824
+ info["min"] = True
825
+
826
+ info_fmt[quarter_start] = "%b"
827
+ info_fmt[year_start] = "%b\n%Y"
828
+
829
+ elif span <= 4 * periodsperyear:
830
+ info_maj[year_start] = True
831
+ info["min"] = True
832
+
833
+ jan_or_jul = (dates_ % 12 == 0) | (dates_ % 12 == 6)
834
+ info_fmt[jan_or_jul] = "%b"
835
+ info_fmt[year_start] = "%b\n%Y"
836
+
837
+ elif span <= 11 * periodsperyear:
838
+ quarter_start = (dates_ % 3 == 0).nonzero()
839
+ info_maj[year_start] = True
840
+ info["min"][quarter_start] = True
841
+
842
+ info_fmt[year_start] = "%Y"
843
+
844
+ else:
845
+ nyears = span / periodsperyear
846
+ (min_anndef, maj_anndef) = _get_default_annual_spacing(nyears)
847
+ years = dates_[year_start] // 12 + 1
848
+ major_idx = year_start[(years % maj_anndef == 0)]
849
+ info_maj[major_idx] = True
850
+ info["min"][year_start[(years % min_anndef == 0)]] = True
851
+
852
+ info_fmt[major_idx] = "%Y"
853
+
854
+ return info
855
+
856
+
857
+ def _quarterly_finder(vmin, vmax, freq: BaseOffset) -> np.ndarray:
858
+ _, _, periodsperyear = _get_periods_per_ymd(freq)
859
+ vmin_orig = vmin
860
+ (vmin, vmax) = (int(vmin), int(vmax))
861
+ span = vmax - vmin + 1
862
+
863
+ info = np.zeros(
864
+ span, dtype=[("val", int), ("maj", bool), ("min", bool), ("fmt", "|S8")]
865
+ )
866
+ info["val"] = np.arange(vmin, vmax + 1)
867
+ info["fmt"] = ""
868
+ dates_ = info["val"]
869
+ info_maj = info["maj"]
870
+ info_fmt = info["fmt"]
871
+ year_start = (dates_ % 4 == 0).nonzero()[0]
872
+
873
+ if span <= 3.5 * periodsperyear:
874
+ info_maj[year_start] = True
875
+ info["min"] = True
876
+
877
+ info_fmt[:] = "Q%q"
878
+ info_fmt[year_start] = "Q%q\n%F"
879
+ if not has_level_label(year_start, vmin_orig):
880
+ if dates_.size > 1:
881
+ idx = 1
882
+ else:
883
+ idx = 0
884
+ info_fmt[idx] = "Q%q\n%F"
885
+
886
+ elif span <= 11 * periodsperyear:
887
+ info_maj[year_start] = True
888
+ info["min"] = True
889
+ info_fmt[year_start] = "%F"
890
+
891
+ else:
892
+ # https://github.com/pandas-dev/pandas/pull/47602
893
+ years = dates_[year_start] // 4 + 1970
894
+ nyears = span / periodsperyear
895
+ (min_anndef, maj_anndef) = _get_default_annual_spacing(nyears)
896
+ major_idx = year_start[(years % maj_anndef == 0)]
897
+ info_maj[major_idx] = True
898
+ info["min"][year_start[(years % min_anndef == 0)]] = True
899
+ info_fmt[major_idx] = "%F"
900
+
901
+ return info
902
+
903
+
904
+ def _annual_finder(vmin, vmax, freq: BaseOffset) -> np.ndarray:
905
+ # Note: small difference here vs other finders in adding 1 to vmax
906
+ (vmin, vmax) = (int(vmin), int(vmax + 1))
907
+ span = vmax - vmin + 1
908
+
909
+ info = np.zeros(
910
+ span, dtype=[("val", int), ("maj", bool), ("min", bool), ("fmt", "|S8")]
911
+ )
912
+ info["val"] = np.arange(vmin, vmax + 1)
913
+ info["fmt"] = ""
914
+ dates_ = info["val"]
915
+
916
+ (min_anndef, maj_anndef) = _get_default_annual_spacing(span)
917
+ major_idx = dates_ % maj_anndef == 0
918
+ minor_idx = dates_ % min_anndef == 0
919
+ info["maj"][major_idx] = True
920
+ info["min"][minor_idx] = True
921
+ info["fmt"][major_idx] = "%Y"
922
+
923
+ return info
924
+
925
+
926
+ def get_finder(freq: BaseOffset):
927
+ # error: "BaseOffset" has no attribute "_period_dtype_code"
928
+ dtype_code = freq._period_dtype_code # type: ignore[attr-defined]
929
+ fgroup = FreqGroup.from_period_dtype_code(dtype_code)
930
+
931
+ if fgroup == FreqGroup.FR_ANN:
932
+ return _annual_finder
933
+ elif fgroup == FreqGroup.FR_QTR:
934
+ return _quarterly_finder
935
+ elif fgroup == FreqGroup.FR_MTH:
936
+ return _monthly_finder
937
+ elif (dtype_code >= FreqGroup.FR_BUS.value) or fgroup == FreqGroup.FR_WK:
938
+ return _daily_finder
939
+ else: # pragma: no cover
940
+ raise NotImplementedError(f"Unsupported frequency: {dtype_code}")
941
+
942
+
943
+ class TimeSeries_DateLocator(Locator):
944
+ """
945
+ Locates the ticks along an axis controlled by a :class:`Series`.
946
+
947
+ Parameters
948
+ ----------
949
+ freq : BaseOffset
950
+ Valid frequency specifier.
951
+ minor_locator : {False, True}, optional
952
+ Whether the locator is for minor ticks (True) or not.
953
+ dynamic_mode : {True, False}, optional
954
+ Whether the locator should work in dynamic mode.
955
+ base : {int}, optional
956
+ quarter : {int}, optional
957
+ month : {int}, optional
958
+ day : {int}, optional
959
+ """
960
+
961
+ axis: Axis
962
+
963
+ def __init__(
964
+ self,
965
+ freq: BaseOffset,
966
+ minor_locator: bool = False,
967
+ dynamic_mode: bool = True,
968
+ base: int = 1,
969
+ quarter: int = 1,
970
+ month: int = 1,
971
+ day: int = 1,
972
+ plot_obj=None,
973
+ ) -> None:
974
+ freq = to_offset(freq, is_period=True)
975
+ self.freq = freq
976
+ self.base = base
977
+ (self.quarter, self.month, self.day) = (quarter, month, day)
978
+ self.isminor = minor_locator
979
+ self.isdynamic = dynamic_mode
980
+ self.offset = 0
981
+ self.plot_obj = plot_obj
982
+ self.finder = get_finder(freq)
983
+
984
+ def _get_default_locs(self, vmin, vmax):
985
+ """Returns the default locations of ticks."""
986
+ locator = self.finder(vmin, vmax, self.freq)
987
+
988
+ if self.isminor:
989
+ return np.compress(locator["min"], locator["val"])
990
+ return np.compress(locator["maj"], locator["val"])
991
+
992
+ def __call__(self):
993
+ """Return the locations of the ticks."""
994
+ # axis calls Locator.set_axis inside set_m<xxxx>_formatter
995
+
996
+ vi = tuple(self.axis.get_view_interval())
997
+ vmin, vmax = vi
998
+ if vmax < vmin:
999
+ vmin, vmax = vmax, vmin
1000
+ if self.isdynamic:
1001
+ locs = self._get_default_locs(vmin, vmax)
1002
+ else: # pragma: no cover
1003
+ base = self.base
1004
+ (d, m) = divmod(vmin, base)
1005
+ vmin = (d + 1) * base
1006
+ # error: No overload variant of "range" matches argument types "float",
1007
+ # "float", "int"
1008
+ locs = list(range(vmin, vmax + 1, base)) # type: ignore[call-overload]
1009
+ return locs
1010
+
1011
+ def autoscale(self):
1012
+ """
1013
+ Sets the view limits to the nearest multiples of base that contain the
1014
+ data.
1015
+ """
1016
+ # requires matplotlib >= 0.98.0
1017
+ (vmin, vmax) = self.axis.get_data_interval()
1018
+
1019
+ locs = self._get_default_locs(vmin, vmax)
1020
+ (vmin, vmax) = locs[[0, -1]]
1021
+ if vmin == vmax:
1022
+ vmin -= 1
1023
+ vmax += 1
1024
+ return nonsingular(vmin, vmax)
1025
+
1026
+
1027
+ # -------------------------------------------------------------------------
1028
+ # --- Formatter ---
1029
+ # -------------------------------------------------------------------------
1030
+
1031
+
1032
+ class TimeSeries_DateFormatter(Formatter):
1033
+ """
1034
+ Formats the ticks along an axis controlled by a :class:`PeriodIndex`.
1035
+
1036
+ Parameters
1037
+ ----------
1038
+ freq : BaseOffset
1039
+ Valid frequency specifier.
1040
+ minor_locator : bool, default False
1041
+ Whether the current formatter should apply to minor ticks (True) or
1042
+ major ticks (False).
1043
+ dynamic_mode : bool, default True
1044
+ Whether the formatter works in dynamic mode or not.
1045
+ """
1046
+
1047
+ axis: Axis
1048
+
1049
+ def __init__(
1050
+ self,
1051
+ freq: BaseOffset,
1052
+ minor_locator: bool = False,
1053
+ dynamic_mode: bool = True,
1054
+ plot_obj=None,
1055
+ ) -> None:
1056
+ freq = to_offset(freq, is_period=True)
1057
+ self.format = None
1058
+ self.freq = freq
1059
+ self.locs: list[Any] = [] # unused, for matplotlib compat
1060
+ self.formatdict: dict[Any, Any] | None = None
1061
+ self.isminor = minor_locator
1062
+ self.isdynamic = dynamic_mode
1063
+ self.offset = 0
1064
+ self.plot_obj = plot_obj
1065
+ self.finder = get_finder(freq)
1066
+
1067
+ def _set_default_format(self, vmin, vmax):
1068
+ """Returns the default ticks spacing."""
1069
+ info = self.finder(vmin, vmax, self.freq)
1070
+
1071
+ if self.isminor:
1072
+ format = np.compress(info["min"] & np.logical_not(info["maj"]), info)
1073
+ else:
1074
+ format = np.compress(info["maj"], info)
1075
+ self.formatdict = {x: f for (x, _, _, f) in format}
1076
+ return self.formatdict
1077
+
1078
+ def set_locs(self, locs) -> None:
1079
+ """Sets the locations of the ticks"""
1080
+ # don't actually use the locs. This is just needed to work with
1081
+ # matplotlib. Force to use vmin, vmax
1082
+
1083
+ self.locs = locs
1084
+
1085
+ (vmin, vmax) = tuple(self.axis.get_view_interval())
1086
+ if vmax < vmin:
1087
+ (vmin, vmax) = (vmax, vmin)
1088
+ self._set_default_format(vmin, vmax)
1089
+
1090
+ def __call__(self, x, pos: int | None = 0) -> str:
1091
+ if self.formatdict is None:
1092
+ return ""
1093
+ else:
1094
+ fmt = self.formatdict.pop(x, "")
1095
+ if isinstance(fmt, np.bytes_):
1096
+ fmt = fmt.decode("utf-8")
1097
+ with warnings.catch_warnings():
1098
+ warnings.filterwarnings(
1099
+ "ignore",
1100
+ "Period with BDay freq is deprecated",
1101
+ category=FutureWarning,
1102
+ )
1103
+ period = Period(ordinal=int(x), freq=self.freq)
1104
+ assert isinstance(period, Period)
1105
+ return period.strftime(fmt)
1106
+
1107
+
1108
+ class TimeSeries_TimedeltaFormatter(Formatter):
1109
+ """
1110
+ Formats the ticks along an axis controlled by a :class:`TimedeltaIndex`.
1111
+ """
1112
+
1113
+ axis: Axis
1114
+
1115
+ @staticmethod
1116
+ def format_timedelta_ticks(x, pos, n_decimals: int) -> str:
1117
+ """
1118
+ Convert seconds to 'D days HH:MM:SS.F'
1119
+ """
1120
+ s, ns = divmod(x, 10**9) # TODO(non-nano): this looks like it assumes ns
1121
+ m, s = divmod(s, 60)
1122
+ h, m = divmod(m, 60)
1123
+ d, h = divmod(h, 24)
1124
+ decimals = int(ns * 10 ** (n_decimals - 9))
1125
+ s = f"{int(h):02d}:{int(m):02d}:{int(s):02d}"
1126
+ if n_decimals > 0:
1127
+ s += f".{decimals:0{n_decimals}d}"
1128
+ if d != 0:
1129
+ s = f"{int(d):d} days {s}"
1130
+ return s
1131
+
1132
+ def __call__(self, x, pos: int | None = 0) -> str:
1133
+ (vmin, vmax) = tuple(self.axis.get_view_interval())
1134
+ n_decimals = min(int(np.ceil(np.log10(100 * 10**9 / abs(vmax - vmin)))), 9)
1135
+ return self.format_timedelta_ticks(x, pos, n_decimals)
venv/lib/python3.10/site-packages/pandas/plotting/_matplotlib/core.py ADDED
@@ -0,0 +1,2119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from abc import (
4
+ ABC,
5
+ abstractmethod,
6
+ )
7
+ from collections.abc import (
8
+ Hashable,
9
+ Iterable,
10
+ Iterator,
11
+ Sequence,
12
+ )
13
+ from typing import (
14
+ TYPE_CHECKING,
15
+ Any,
16
+ Literal,
17
+ cast,
18
+ final,
19
+ )
20
+ import warnings
21
+
22
+ import matplotlib as mpl
23
+ import numpy as np
24
+
25
+ from pandas._libs import lib
26
+ from pandas.errors import AbstractMethodError
27
+ from pandas.util._decorators import cache_readonly
28
+ from pandas.util._exceptions import find_stack_level
29
+
30
+ from pandas.core.dtypes.common import (
31
+ is_any_real_numeric_dtype,
32
+ is_bool,
33
+ is_float,
34
+ is_float_dtype,
35
+ is_hashable,
36
+ is_integer,
37
+ is_integer_dtype,
38
+ is_iterator,
39
+ is_list_like,
40
+ is_number,
41
+ is_numeric_dtype,
42
+ )
43
+ from pandas.core.dtypes.dtypes import (
44
+ CategoricalDtype,
45
+ ExtensionDtype,
46
+ )
47
+ from pandas.core.dtypes.generic import (
48
+ ABCDataFrame,
49
+ ABCDatetimeIndex,
50
+ ABCIndex,
51
+ ABCMultiIndex,
52
+ ABCPeriodIndex,
53
+ ABCSeries,
54
+ )
55
+ from pandas.core.dtypes.missing import isna
56
+
57
+ import pandas.core.common as com
58
+ from pandas.core.frame import DataFrame
59
+ from pandas.util.version import Version
60
+
61
+ from pandas.io.formats.printing import pprint_thing
62
+ from pandas.plotting._matplotlib import tools
63
+ from pandas.plotting._matplotlib.converter import register_pandas_matplotlib_converters
64
+ from pandas.plotting._matplotlib.groupby import reconstruct_data_with_by
65
+ from pandas.plotting._matplotlib.misc import unpack_single_str_list
66
+ from pandas.plotting._matplotlib.style import get_standard_colors
67
+ from pandas.plotting._matplotlib.timeseries import (
68
+ decorate_axes,
69
+ format_dateaxis,
70
+ maybe_convert_index,
71
+ maybe_resample,
72
+ use_dynamic_x,
73
+ )
74
+ from pandas.plotting._matplotlib.tools import (
75
+ create_subplots,
76
+ flatten_axes,
77
+ format_date_labels,
78
+ get_all_lines,
79
+ get_xlim,
80
+ handle_shared_axes,
81
+ )
82
+
83
+ if TYPE_CHECKING:
84
+ from matplotlib.artist import Artist
85
+ from matplotlib.axes import Axes
86
+ from matplotlib.axis import Axis
87
+ from matplotlib.figure import Figure
88
+
89
+ from pandas._typing import (
90
+ IndexLabel,
91
+ NDFrameT,
92
+ PlottingOrientation,
93
+ npt,
94
+ )
95
+
96
+ from pandas import Series
97
+
98
+
99
+ def _color_in_style(style: str) -> bool:
100
+ """
101
+ Check if there is a color letter in the style string.
102
+ """
103
+ from matplotlib.colors import BASE_COLORS
104
+
105
+ return not set(BASE_COLORS).isdisjoint(style)
106
+
107
+
108
+ class MPLPlot(ABC):
109
+ """
110
+ Base class for assembling a pandas plot using matplotlib
111
+
112
+ Parameters
113
+ ----------
114
+ data :
115
+
116
+ """
117
+
118
+ @property
119
+ @abstractmethod
120
+ def _kind(self) -> str:
121
+ """Specify kind str. Must be overridden in child class"""
122
+ raise NotImplementedError
123
+
124
+ _layout_type = "vertical"
125
+ _default_rot = 0
126
+
127
+ @property
128
+ def orientation(self) -> str | None:
129
+ return None
130
+
131
+ data: DataFrame
132
+
133
+ def __init__(
134
+ self,
135
+ data,
136
+ kind=None,
137
+ by: IndexLabel | None = None,
138
+ subplots: bool | Sequence[Sequence[str]] = False,
139
+ sharex: bool | None = None,
140
+ sharey: bool = False,
141
+ use_index: bool = True,
142
+ figsize: tuple[float, float] | None = None,
143
+ grid=None,
144
+ legend: bool | str = True,
145
+ rot=None,
146
+ ax=None,
147
+ fig=None,
148
+ title=None,
149
+ xlim=None,
150
+ ylim=None,
151
+ xticks=None,
152
+ yticks=None,
153
+ xlabel: Hashable | None = None,
154
+ ylabel: Hashable | None = None,
155
+ fontsize: int | None = None,
156
+ secondary_y: bool | tuple | list | np.ndarray = False,
157
+ colormap=None,
158
+ table: bool = False,
159
+ layout=None,
160
+ include_bool: bool = False,
161
+ column: IndexLabel | None = None,
162
+ *,
163
+ logx: bool | None | Literal["sym"] = False,
164
+ logy: bool | None | Literal["sym"] = False,
165
+ loglog: bool | None | Literal["sym"] = False,
166
+ mark_right: bool = True,
167
+ stacked: bool = False,
168
+ label: Hashable | None = None,
169
+ style=None,
170
+ **kwds,
171
+ ) -> None:
172
+ import matplotlib.pyplot as plt
173
+
174
+ # if users assign an empty list or tuple, raise `ValueError`
175
+ # similar to current `df.box` and `df.hist` APIs.
176
+ if by in ([], ()):
177
+ raise ValueError("No group keys passed!")
178
+ self.by = com.maybe_make_list(by)
179
+
180
+ # Assign the rest of columns into self.columns if by is explicitly defined
181
+ # while column is not, only need `columns` in hist/box plot when it's DF
182
+ # TODO: Might deprecate `column` argument in future PR (#28373)
183
+ if isinstance(data, DataFrame):
184
+ if column:
185
+ self.columns = com.maybe_make_list(column)
186
+ elif self.by is None:
187
+ self.columns = [
188
+ col for col in data.columns if is_numeric_dtype(data[col])
189
+ ]
190
+ else:
191
+ self.columns = [
192
+ col
193
+ for col in data.columns
194
+ if col not in self.by and is_numeric_dtype(data[col])
195
+ ]
196
+
197
+ # For `hist` plot, need to get grouped original data before `self.data` is
198
+ # updated later
199
+ if self.by is not None and self._kind == "hist":
200
+ self._grouped = data.groupby(unpack_single_str_list(self.by))
201
+
202
+ self.kind = kind
203
+
204
+ self.subplots = type(self)._validate_subplots_kwarg(
205
+ subplots, data, kind=self._kind
206
+ )
207
+
208
+ self.sharex = type(self)._validate_sharex(sharex, ax, by)
209
+ self.sharey = sharey
210
+ self.figsize = figsize
211
+ self.layout = layout
212
+
213
+ self.xticks = xticks
214
+ self.yticks = yticks
215
+ self.xlim = xlim
216
+ self.ylim = ylim
217
+ self.title = title
218
+ self.use_index = use_index
219
+ self.xlabel = xlabel
220
+ self.ylabel = ylabel
221
+
222
+ self.fontsize = fontsize
223
+
224
+ if rot is not None:
225
+ self.rot = rot
226
+ # need to know for format_date_labels since it's rotated to 30 by
227
+ # default
228
+ self._rot_set = True
229
+ else:
230
+ self._rot_set = False
231
+ self.rot = self._default_rot
232
+
233
+ if grid is None:
234
+ grid = False if secondary_y else plt.rcParams["axes.grid"]
235
+
236
+ self.grid = grid
237
+ self.legend = legend
238
+ self.legend_handles: list[Artist] = []
239
+ self.legend_labels: list[Hashable] = []
240
+
241
+ self.logx = type(self)._validate_log_kwd("logx", logx)
242
+ self.logy = type(self)._validate_log_kwd("logy", logy)
243
+ self.loglog = type(self)._validate_log_kwd("loglog", loglog)
244
+ self.label = label
245
+ self.style = style
246
+ self.mark_right = mark_right
247
+ self.stacked = stacked
248
+
249
+ # ax may be an Axes object or (if self.subplots) an ndarray of
250
+ # Axes objects
251
+ self.ax = ax
252
+ # TODO: deprecate fig keyword as it is ignored, not passed in tests
253
+ # as of 2023-11-05
254
+
255
+ # parse errorbar input if given
256
+ xerr = kwds.pop("xerr", None)
257
+ yerr = kwds.pop("yerr", None)
258
+ nseries = self._get_nseries(data)
259
+ xerr, data = type(self)._parse_errorbars("xerr", xerr, data, nseries)
260
+ yerr, data = type(self)._parse_errorbars("yerr", yerr, data, nseries)
261
+ self.errors = {"xerr": xerr, "yerr": yerr}
262
+ self.data = data
263
+
264
+ if not isinstance(secondary_y, (bool, tuple, list, np.ndarray, ABCIndex)):
265
+ secondary_y = [secondary_y]
266
+ self.secondary_y = secondary_y
267
+
268
+ # ugly TypeError if user passes matplotlib's `cmap` name.
269
+ # Probably better to accept either.
270
+ if "cmap" in kwds and colormap:
271
+ raise TypeError("Only specify one of `cmap` and `colormap`.")
272
+ if "cmap" in kwds:
273
+ self.colormap = kwds.pop("cmap")
274
+ else:
275
+ self.colormap = colormap
276
+
277
+ self.table = table
278
+ self.include_bool = include_bool
279
+
280
+ self.kwds = kwds
281
+
282
+ color = kwds.pop("color", lib.no_default)
283
+ self.color = self._validate_color_args(color, self.colormap)
284
+ assert "color" not in self.kwds
285
+
286
+ self.data = self._ensure_frame(self.data)
287
+
288
+ @final
289
+ @staticmethod
290
+ def _validate_sharex(sharex: bool | None, ax, by) -> bool:
291
+ if sharex is None:
292
+ # if by is defined, subplots are used and sharex should be False
293
+ if ax is None and by is None: # pylint: disable=simplifiable-if-statement
294
+ sharex = True
295
+ else:
296
+ # if we get an axis, the users should do the visibility
297
+ # setting...
298
+ sharex = False
299
+ elif not is_bool(sharex):
300
+ raise TypeError("sharex must be a bool or None")
301
+ return bool(sharex)
302
+
303
+ @classmethod
304
+ def _validate_log_kwd(
305
+ cls,
306
+ kwd: str,
307
+ value: bool | None | Literal["sym"],
308
+ ) -> bool | None | Literal["sym"]:
309
+ if (
310
+ value is None
311
+ or isinstance(value, bool)
312
+ or (isinstance(value, str) and value == "sym")
313
+ ):
314
+ return value
315
+ raise ValueError(
316
+ f"keyword '{kwd}' should be bool, None, or 'sym', not '{value}'"
317
+ )
318
+
319
+ @final
320
+ @staticmethod
321
+ def _validate_subplots_kwarg(
322
+ subplots: bool | Sequence[Sequence[str]], data: Series | DataFrame, kind: str
323
+ ) -> bool | list[tuple[int, ...]]:
324
+ """
325
+ Validate the subplots parameter
326
+
327
+ - check type and content
328
+ - check for duplicate columns
329
+ - check for invalid column names
330
+ - convert column names into indices
331
+ - add missing columns in a group of their own
332
+ See comments in code below for more details.
333
+
334
+ Parameters
335
+ ----------
336
+ subplots : subplots parameters as passed to PlotAccessor
337
+
338
+ Returns
339
+ -------
340
+ validated subplots : a bool or a list of tuples of column indices. Columns
341
+ in the same tuple will be grouped together in the resulting plot.
342
+ """
343
+
344
+ if isinstance(subplots, bool):
345
+ return subplots
346
+ elif not isinstance(subplots, Iterable):
347
+ raise ValueError("subplots should be a bool or an iterable")
348
+
349
+ supported_kinds = (
350
+ "line",
351
+ "bar",
352
+ "barh",
353
+ "hist",
354
+ "kde",
355
+ "density",
356
+ "area",
357
+ "pie",
358
+ )
359
+ if kind not in supported_kinds:
360
+ raise ValueError(
361
+ "When subplots is an iterable, kind must be "
362
+ f"one of {', '.join(supported_kinds)}. Got {kind}."
363
+ )
364
+
365
+ if isinstance(data, ABCSeries):
366
+ raise NotImplementedError(
367
+ "An iterable subplots for a Series is not supported."
368
+ )
369
+
370
+ columns = data.columns
371
+ if isinstance(columns, ABCMultiIndex):
372
+ raise NotImplementedError(
373
+ "An iterable subplots for a DataFrame with a MultiIndex column "
374
+ "is not supported."
375
+ )
376
+
377
+ if columns.nunique() != len(columns):
378
+ raise NotImplementedError(
379
+ "An iterable subplots for a DataFrame with non-unique column "
380
+ "labels is not supported."
381
+ )
382
+
383
+ # subplots is a list of tuples where each tuple is a group of
384
+ # columns to be grouped together (one ax per group).
385
+ # we consolidate the subplots list such that:
386
+ # - the tuples contain indices instead of column names
387
+ # - the columns that aren't yet in the list are added in a group
388
+ # of their own.
389
+ # For example with columns from a to g, and
390
+ # subplots = [(a, c), (b, f, e)],
391
+ # we end up with [(ai, ci), (bi, fi, ei), (di,), (gi,)]
392
+ # This way, we can handle self.subplots in a homogeneous manner
393
+ # later.
394
+ # TODO: also accept indices instead of just names?
395
+
396
+ out = []
397
+ seen_columns: set[Hashable] = set()
398
+ for group in subplots:
399
+ if not is_list_like(group):
400
+ raise ValueError(
401
+ "When subplots is an iterable, each entry "
402
+ "should be a list/tuple of column names."
403
+ )
404
+ idx_locs = columns.get_indexer_for(group)
405
+ if (idx_locs == -1).any():
406
+ bad_labels = np.extract(idx_locs == -1, group)
407
+ raise ValueError(
408
+ f"Column label(s) {list(bad_labels)} not found in the DataFrame."
409
+ )
410
+ unique_columns = set(group)
411
+ duplicates = seen_columns.intersection(unique_columns)
412
+ if duplicates:
413
+ raise ValueError(
414
+ "Each column should be in only one subplot. "
415
+ f"Columns {duplicates} were found in multiple subplots."
416
+ )
417
+ seen_columns = seen_columns.union(unique_columns)
418
+ out.append(tuple(idx_locs))
419
+
420
+ unseen_columns = columns.difference(seen_columns)
421
+ for column in unseen_columns:
422
+ idx_loc = columns.get_loc(column)
423
+ out.append((idx_loc,))
424
+ return out
425
+
426
+ def _validate_color_args(self, color, colormap):
427
+ if color is lib.no_default:
428
+ # It was not provided by the user
429
+ if "colors" in self.kwds and colormap is not None:
430
+ warnings.warn(
431
+ "'color' and 'colormap' cannot be used simultaneously. "
432
+ "Using 'color'",
433
+ stacklevel=find_stack_level(),
434
+ )
435
+ return None
436
+ if self.nseries == 1 and color is not None and not is_list_like(color):
437
+ # support series.plot(color='green')
438
+ color = [color]
439
+
440
+ if isinstance(color, tuple) and self.nseries == 1 and len(color) in (3, 4):
441
+ # support RGB and RGBA tuples in series plot
442
+ color = [color]
443
+
444
+ if colormap is not None:
445
+ warnings.warn(
446
+ "'color' and 'colormap' cannot be used simultaneously. Using 'color'",
447
+ stacklevel=find_stack_level(),
448
+ )
449
+
450
+ if self.style is not None:
451
+ if is_list_like(self.style):
452
+ styles = self.style
453
+ else:
454
+ styles = [self.style]
455
+ # need only a single match
456
+ for s in styles:
457
+ if _color_in_style(s):
458
+ raise ValueError(
459
+ "Cannot pass 'style' string with a color symbol and "
460
+ "'color' keyword argument. Please use one or the "
461
+ "other or pass 'style' without a color symbol"
462
+ )
463
+ return color
464
+
465
+ @final
466
+ @staticmethod
467
+ def _iter_data(
468
+ data: DataFrame | dict[Hashable, Series | DataFrame]
469
+ ) -> Iterator[tuple[Hashable, np.ndarray]]:
470
+ for col, values in data.items():
471
+ # This was originally written to use values.values before EAs
472
+ # were implemented; adding np.asarray(...) to keep consistent
473
+ # typing.
474
+ yield col, np.asarray(values.values)
475
+
476
+ def _get_nseries(self, data: Series | DataFrame) -> int:
477
+ # When `by` is explicitly assigned, grouped data size will be defined, and
478
+ # this will determine number of subplots to have, aka `self.nseries`
479
+ if data.ndim == 1:
480
+ return 1
481
+ elif self.by is not None and self._kind == "hist":
482
+ return len(self._grouped)
483
+ elif self.by is not None and self._kind == "box":
484
+ return len(self.columns)
485
+ else:
486
+ return data.shape[1]
487
+
488
+ @final
489
+ @property
490
+ def nseries(self) -> int:
491
+ return self._get_nseries(self.data)
492
+
493
+ @final
494
+ def draw(self) -> None:
495
+ self.plt.draw_if_interactive()
496
+
497
+ @final
498
+ def generate(self) -> None:
499
+ self._compute_plot_data()
500
+ fig = self.fig
501
+ self._make_plot(fig)
502
+ self._add_table()
503
+ self._make_legend()
504
+ self._adorn_subplots(fig)
505
+
506
+ for ax in self.axes:
507
+ self._post_plot_logic_common(ax)
508
+ self._post_plot_logic(ax, self.data)
509
+
510
+ @final
511
+ @staticmethod
512
+ def _has_plotted_object(ax: Axes) -> bool:
513
+ """check whether ax has data"""
514
+ return len(ax.lines) != 0 or len(ax.artists) != 0 or len(ax.containers) != 0
515
+
516
+ @final
517
+ def _maybe_right_yaxis(self, ax: Axes, axes_num: int) -> Axes:
518
+ if not self.on_right(axes_num):
519
+ # secondary axes may be passed via ax kw
520
+ return self._get_ax_layer(ax)
521
+
522
+ if hasattr(ax, "right_ax"):
523
+ # if it has right_ax property, ``ax`` must be left axes
524
+ return ax.right_ax
525
+ elif hasattr(ax, "left_ax"):
526
+ # if it has left_ax property, ``ax`` must be right axes
527
+ return ax
528
+ else:
529
+ # otherwise, create twin axes
530
+ orig_ax, new_ax = ax, ax.twinx()
531
+ # TODO: use Matplotlib public API when available
532
+ new_ax._get_lines = orig_ax._get_lines # type: ignore[attr-defined]
533
+ # TODO #54485
534
+ new_ax._get_patches_for_fill = ( # type: ignore[attr-defined]
535
+ orig_ax._get_patches_for_fill # type: ignore[attr-defined]
536
+ )
537
+ # TODO #54485
538
+ orig_ax.right_ax, new_ax.left_ax = ( # type: ignore[attr-defined]
539
+ new_ax,
540
+ orig_ax,
541
+ )
542
+
543
+ if not self._has_plotted_object(orig_ax): # no data on left y
544
+ orig_ax.get_yaxis().set_visible(False)
545
+
546
+ if self.logy is True or self.loglog is True:
547
+ new_ax.set_yscale("log")
548
+ elif self.logy == "sym" or self.loglog == "sym":
549
+ new_ax.set_yscale("symlog")
550
+ return new_ax # type: ignore[return-value]
551
+
552
+ @final
553
+ @cache_readonly
554
+ def fig(self) -> Figure:
555
+ return self._axes_and_fig[1]
556
+
557
+ @final
558
+ @cache_readonly
559
+ # TODO: can we annotate this as both a Sequence[Axes] and ndarray[object]?
560
+ def axes(self) -> Sequence[Axes]:
561
+ return self._axes_and_fig[0]
562
+
563
+ @final
564
+ @cache_readonly
565
+ def _axes_and_fig(self) -> tuple[Sequence[Axes], Figure]:
566
+ if self.subplots:
567
+ naxes = (
568
+ self.nseries if isinstance(self.subplots, bool) else len(self.subplots)
569
+ )
570
+ fig, axes = create_subplots(
571
+ naxes=naxes,
572
+ sharex=self.sharex,
573
+ sharey=self.sharey,
574
+ figsize=self.figsize,
575
+ ax=self.ax,
576
+ layout=self.layout,
577
+ layout_type=self._layout_type,
578
+ )
579
+ elif self.ax is None:
580
+ fig = self.plt.figure(figsize=self.figsize)
581
+ axes = fig.add_subplot(111)
582
+ else:
583
+ fig = self.ax.get_figure()
584
+ if self.figsize is not None:
585
+ fig.set_size_inches(self.figsize)
586
+ axes = self.ax
587
+
588
+ axes = flatten_axes(axes)
589
+
590
+ if self.logx is True or self.loglog is True:
591
+ [a.set_xscale("log") for a in axes]
592
+ elif self.logx == "sym" or self.loglog == "sym":
593
+ [a.set_xscale("symlog") for a in axes]
594
+
595
+ if self.logy is True or self.loglog is True:
596
+ [a.set_yscale("log") for a in axes]
597
+ elif self.logy == "sym" or self.loglog == "sym":
598
+ [a.set_yscale("symlog") for a in axes]
599
+
600
+ axes_seq = cast(Sequence["Axes"], axes)
601
+ return axes_seq, fig
602
+
603
+ @property
604
+ def result(self):
605
+ """
606
+ Return result axes
607
+ """
608
+ if self.subplots:
609
+ if self.layout is not None and not is_list_like(self.ax):
610
+ # error: "Sequence[Any]" has no attribute "reshape"
611
+ return self.axes.reshape(*self.layout) # type: ignore[attr-defined]
612
+ else:
613
+ return self.axes
614
+ else:
615
+ sec_true = isinstance(self.secondary_y, bool) and self.secondary_y
616
+ # error: Argument 1 to "len" has incompatible type "Union[bool,
617
+ # Tuple[Any, ...], List[Any], ndarray[Any, Any]]"; expected "Sized"
618
+ all_sec = (
619
+ is_list_like(self.secondary_y)
620
+ and len(self.secondary_y) == self.nseries # type: ignore[arg-type]
621
+ )
622
+ if sec_true or all_sec:
623
+ # if all data is plotted on secondary, return right axes
624
+ return self._get_ax_layer(self.axes[0], primary=False)
625
+ else:
626
+ return self.axes[0]
627
+
628
+ @final
629
+ @staticmethod
630
+ def _convert_to_ndarray(data):
631
+ # GH31357: categorical columns are processed separately
632
+ if isinstance(data.dtype, CategoricalDtype):
633
+ return data
634
+
635
+ # GH32073: cast to float if values contain nulled integers
636
+ if (is_integer_dtype(data.dtype) or is_float_dtype(data.dtype)) and isinstance(
637
+ data.dtype, ExtensionDtype
638
+ ):
639
+ return data.to_numpy(dtype="float", na_value=np.nan)
640
+
641
+ # GH25587: cast ExtensionArray of pandas (IntegerArray, etc.) to
642
+ # np.ndarray before plot.
643
+ if len(data) > 0:
644
+ return np.asarray(data)
645
+
646
+ return data
647
+
648
+ @final
649
+ def _ensure_frame(self, data) -> DataFrame:
650
+ if isinstance(data, ABCSeries):
651
+ label = self.label
652
+ if label is None and data.name is None:
653
+ label = ""
654
+ if label is None:
655
+ # We'll end up with columns of [0] instead of [None]
656
+ data = data.to_frame()
657
+ else:
658
+ data = data.to_frame(name=label)
659
+ elif self._kind in ("hist", "box"):
660
+ cols = self.columns if self.by is None else self.columns + self.by
661
+ data = data.loc[:, cols]
662
+ return data
663
+
664
+ @final
665
+ def _compute_plot_data(self) -> None:
666
+ data = self.data
667
+
668
+ # GH15079 reconstruct data if by is defined
669
+ if self.by is not None:
670
+ self.subplots = True
671
+ data = reconstruct_data_with_by(self.data, by=self.by, cols=self.columns)
672
+
673
+ # GH16953, infer_objects is needed as fallback, for ``Series``
674
+ # with ``dtype == object``
675
+ data = data.infer_objects(copy=False)
676
+ include_type = [np.number, "datetime", "datetimetz", "timedelta"]
677
+
678
+ # GH23719, allow plotting boolean
679
+ if self.include_bool is True:
680
+ include_type.append(np.bool_)
681
+
682
+ # GH22799, exclude datetime-like type for boxplot
683
+ exclude_type = None
684
+ if self._kind == "box":
685
+ # TODO: change after solving issue 27881
686
+ include_type = [np.number]
687
+ exclude_type = ["timedelta"]
688
+
689
+ # GH 18755, include object and category type for scatter plot
690
+ if self._kind == "scatter":
691
+ include_type.extend(["object", "category", "string"])
692
+
693
+ numeric_data = data.select_dtypes(include=include_type, exclude=exclude_type)
694
+
695
+ is_empty = numeric_data.shape[-1] == 0
696
+ # no non-numeric frames or series allowed
697
+ if is_empty:
698
+ raise TypeError("no numeric data to plot")
699
+
700
+ self.data = numeric_data.apply(type(self)._convert_to_ndarray)
701
+
702
+ def _make_plot(self, fig: Figure) -> None:
703
+ raise AbstractMethodError(self)
704
+
705
+ @final
706
+ def _add_table(self) -> None:
707
+ if self.table is False:
708
+ return
709
+ elif self.table is True:
710
+ data = self.data.transpose()
711
+ else:
712
+ data = self.table
713
+ ax = self._get_ax(0)
714
+ tools.table(ax, data)
715
+
716
+ @final
717
+ def _post_plot_logic_common(self, ax: Axes) -> None:
718
+ """Common post process for each axes"""
719
+ if self.orientation == "vertical" or self.orientation is None:
720
+ type(self)._apply_axis_properties(
721
+ ax.xaxis, rot=self.rot, fontsize=self.fontsize
722
+ )
723
+ type(self)._apply_axis_properties(ax.yaxis, fontsize=self.fontsize)
724
+
725
+ if hasattr(ax, "right_ax"):
726
+ type(self)._apply_axis_properties(
727
+ ax.right_ax.yaxis, fontsize=self.fontsize
728
+ )
729
+
730
+ elif self.orientation == "horizontal":
731
+ type(self)._apply_axis_properties(
732
+ ax.yaxis, rot=self.rot, fontsize=self.fontsize
733
+ )
734
+ type(self)._apply_axis_properties(ax.xaxis, fontsize=self.fontsize)
735
+
736
+ if hasattr(ax, "right_ax"):
737
+ type(self)._apply_axis_properties(
738
+ ax.right_ax.yaxis, fontsize=self.fontsize
739
+ )
740
+ else: # pragma no cover
741
+ raise ValueError
742
+
743
+ @abstractmethod
744
+ def _post_plot_logic(self, ax: Axes, data) -> None:
745
+ """Post process for each axes. Overridden in child classes"""
746
+
747
+ @final
748
+ def _adorn_subplots(self, fig: Figure) -> None:
749
+ """Common post process unrelated to data"""
750
+ if len(self.axes) > 0:
751
+ all_axes = self._get_subplots(fig)
752
+ nrows, ncols = self._get_axes_layout(fig)
753
+ handle_shared_axes(
754
+ axarr=all_axes,
755
+ nplots=len(all_axes),
756
+ naxes=nrows * ncols,
757
+ nrows=nrows,
758
+ ncols=ncols,
759
+ sharex=self.sharex,
760
+ sharey=self.sharey,
761
+ )
762
+
763
+ for ax in self.axes:
764
+ ax = getattr(ax, "right_ax", ax)
765
+ if self.yticks is not None:
766
+ ax.set_yticks(self.yticks)
767
+
768
+ if self.xticks is not None:
769
+ ax.set_xticks(self.xticks)
770
+
771
+ if self.ylim is not None:
772
+ ax.set_ylim(self.ylim)
773
+
774
+ if self.xlim is not None:
775
+ ax.set_xlim(self.xlim)
776
+
777
+ # GH9093, currently Pandas does not show ylabel, so if users provide
778
+ # ylabel will set it as ylabel in the plot.
779
+ if self.ylabel is not None:
780
+ ax.set_ylabel(pprint_thing(self.ylabel))
781
+
782
+ ax.grid(self.grid)
783
+
784
+ if self.title:
785
+ if self.subplots:
786
+ if is_list_like(self.title):
787
+ if len(self.title) != self.nseries:
788
+ raise ValueError(
789
+ "The length of `title` must equal the number "
790
+ "of columns if using `title` of type `list` "
791
+ "and `subplots=True`.\n"
792
+ f"length of title = {len(self.title)}\n"
793
+ f"number of columns = {self.nseries}"
794
+ )
795
+
796
+ for ax, title in zip(self.axes, self.title):
797
+ ax.set_title(title)
798
+ else:
799
+ fig.suptitle(self.title)
800
+ else:
801
+ if is_list_like(self.title):
802
+ msg = (
803
+ "Using `title` of type `list` is not supported "
804
+ "unless `subplots=True` is passed"
805
+ )
806
+ raise ValueError(msg)
807
+ self.axes[0].set_title(self.title)
808
+
809
+ @final
810
+ @staticmethod
811
+ def _apply_axis_properties(
812
+ axis: Axis, rot=None, fontsize: int | None = None
813
+ ) -> None:
814
+ """
815
+ Tick creation within matplotlib is reasonably expensive and is
816
+ internally deferred until accessed as Ticks are created/destroyed
817
+ multiple times per draw. It's therefore beneficial for us to avoid
818
+ accessing unless we will act on the Tick.
819
+ """
820
+ if rot is not None or fontsize is not None:
821
+ # rot=0 is a valid setting, hence the explicit None check
822
+ labels = axis.get_majorticklabels() + axis.get_minorticklabels()
823
+ for label in labels:
824
+ if rot is not None:
825
+ label.set_rotation(rot)
826
+ if fontsize is not None:
827
+ label.set_fontsize(fontsize)
828
+
829
+ @final
830
+ @property
831
+ def legend_title(self) -> str | None:
832
+ if not isinstance(self.data.columns, ABCMultiIndex):
833
+ name = self.data.columns.name
834
+ if name is not None:
835
+ name = pprint_thing(name)
836
+ return name
837
+ else:
838
+ stringified = map(pprint_thing, self.data.columns.names)
839
+ return ",".join(stringified)
840
+
841
+ @final
842
+ def _mark_right_label(self, label: str, index: int) -> str:
843
+ """
844
+ Append ``(right)`` to the label of a line if it's plotted on the right axis.
845
+
846
+ Note that ``(right)`` is only appended when ``subplots=False``.
847
+ """
848
+ if not self.subplots and self.mark_right and self.on_right(index):
849
+ label += " (right)"
850
+ return label
851
+
852
+ @final
853
+ def _append_legend_handles_labels(self, handle: Artist, label: str) -> None:
854
+ """
855
+ Append current handle and label to ``legend_handles`` and ``legend_labels``.
856
+
857
+ These will be used to make the legend.
858
+ """
859
+ self.legend_handles.append(handle)
860
+ self.legend_labels.append(label)
861
+
862
+ def _make_legend(self) -> None:
863
+ ax, leg = self._get_ax_legend(self.axes[0])
864
+
865
+ handles = []
866
+ labels = []
867
+ title = ""
868
+
869
+ if not self.subplots:
870
+ if leg is not None:
871
+ title = leg.get_title().get_text()
872
+ # Replace leg.legend_handles because it misses marker info
873
+ if Version(mpl.__version__) < Version("3.7"):
874
+ handles = leg.legendHandles
875
+ else:
876
+ handles = leg.legend_handles
877
+ labels = [x.get_text() for x in leg.get_texts()]
878
+
879
+ if self.legend:
880
+ if self.legend == "reverse":
881
+ handles += reversed(self.legend_handles)
882
+ labels += reversed(self.legend_labels)
883
+ else:
884
+ handles += self.legend_handles
885
+ labels += self.legend_labels
886
+
887
+ if self.legend_title is not None:
888
+ title = self.legend_title
889
+
890
+ if len(handles) > 0:
891
+ ax.legend(handles, labels, loc="best", title=title)
892
+
893
+ elif self.subplots and self.legend:
894
+ for ax in self.axes:
895
+ if ax.get_visible():
896
+ ax.legend(loc="best")
897
+
898
+ @final
899
+ @staticmethod
900
+ def _get_ax_legend(ax: Axes):
901
+ """
902
+ Take in axes and return ax and legend under different scenarios
903
+ """
904
+ leg = ax.get_legend()
905
+
906
+ other_ax = getattr(ax, "left_ax", None) or getattr(ax, "right_ax", None)
907
+ other_leg = None
908
+ if other_ax is not None:
909
+ other_leg = other_ax.get_legend()
910
+ if leg is None and other_leg is not None:
911
+ leg = other_leg
912
+ ax = other_ax
913
+ return ax, leg
914
+
915
+ @final
916
+ @cache_readonly
917
+ def plt(self):
918
+ import matplotlib.pyplot as plt
919
+
920
+ return plt
921
+
922
+ _need_to_set_index = False
923
+
924
+ @final
925
+ def _get_xticks(self):
926
+ index = self.data.index
927
+ is_datetype = index.inferred_type in ("datetime", "date", "datetime64", "time")
928
+
929
+ # TODO: be stricter about x?
930
+ x: list[int] | np.ndarray
931
+ if self.use_index:
932
+ if isinstance(index, ABCPeriodIndex):
933
+ # test_mixed_freq_irreg_period
934
+ x = index.to_timestamp()._mpl_repr()
935
+ # TODO: why do we need to do to_timestamp() here but not other
936
+ # places where we call mpl_repr?
937
+ elif is_any_real_numeric_dtype(index.dtype):
938
+ # Matplotlib supports numeric values or datetime objects as
939
+ # xaxis values. Taking LBYL approach here, by the time
940
+ # matplotlib raises exception when using non numeric/datetime
941
+ # values for xaxis, several actions are already taken by plt.
942
+ x = index._mpl_repr()
943
+ elif isinstance(index, ABCDatetimeIndex) or is_datetype:
944
+ x = index._mpl_repr()
945
+ else:
946
+ self._need_to_set_index = True
947
+ x = list(range(len(index)))
948
+ else:
949
+ x = list(range(len(index)))
950
+
951
+ return x
952
+
953
+ @classmethod
954
+ @register_pandas_matplotlib_converters
955
+ def _plot(
956
+ cls, ax: Axes, x, y: np.ndarray, style=None, is_errorbar: bool = False, **kwds
957
+ ):
958
+ mask = isna(y)
959
+ if mask.any():
960
+ y = np.ma.array(y)
961
+ y = np.ma.masked_where(mask, y)
962
+
963
+ if isinstance(x, ABCIndex):
964
+ x = x._mpl_repr()
965
+
966
+ if is_errorbar:
967
+ if "xerr" in kwds:
968
+ kwds["xerr"] = np.array(kwds.get("xerr"))
969
+ if "yerr" in kwds:
970
+ kwds["yerr"] = np.array(kwds.get("yerr"))
971
+ return ax.errorbar(x, y, **kwds)
972
+ else:
973
+ # prevent style kwarg from going to errorbar, where it is unsupported
974
+ args = (x, y, style) if style is not None else (x, y)
975
+ return ax.plot(*args, **kwds)
976
+
977
+ def _get_custom_index_name(self):
978
+ """Specify whether xlabel/ylabel should be used to override index name"""
979
+ return self.xlabel
980
+
981
+ @final
982
+ def _get_index_name(self) -> str | None:
983
+ if isinstance(self.data.index, ABCMultiIndex):
984
+ name = self.data.index.names
985
+ if com.any_not_none(*name):
986
+ name = ",".join([pprint_thing(x) for x in name])
987
+ else:
988
+ name = None
989
+ else:
990
+ name = self.data.index.name
991
+ if name is not None:
992
+ name = pprint_thing(name)
993
+
994
+ # GH 45145, override the default axis label if one is provided.
995
+ index_name = self._get_custom_index_name()
996
+ if index_name is not None:
997
+ name = pprint_thing(index_name)
998
+
999
+ return name
1000
+
1001
+ @final
1002
+ @classmethod
1003
+ def _get_ax_layer(cls, ax, primary: bool = True):
1004
+ """get left (primary) or right (secondary) axes"""
1005
+ if primary:
1006
+ return getattr(ax, "left_ax", ax)
1007
+ else:
1008
+ return getattr(ax, "right_ax", ax)
1009
+
1010
+ @final
1011
+ def _col_idx_to_axis_idx(self, col_idx: int) -> int:
1012
+ """Return the index of the axis where the column at col_idx should be plotted"""
1013
+ if isinstance(self.subplots, list):
1014
+ # Subplots is a list: some columns will be grouped together in the same ax
1015
+ return next(
1016
+ group_idx
1017
+ for (group_idx, group) in enumerate(self.subplots)
1018
+ if col_idx in group
1019
+ )
1020
+ else:
1021
+ # subplots is True: one ax per column
1022
+ return col_idx
1023
+
1024
+ @final
1025
+ def _get_ax(self, i: int):
1026
+ # get the twinx ax if appropriate
1027
+ if self.subplots:
1028
+ i = self._col_idx_to_axis_idx(i)
1029
+ ax = self.axes[i]
1030
+ ax = self._maybe_right_yaxis(ax, i)
1031
+ # error: Unsupported target for indexed assignment ("Sequence[Any]")
1032
+ self.axes[i] = ax # type: ignore[index]
1033
+ else:
1034
+ ax = self.axes[0]
1035
+ ax = self._maybe_right_yaxis(ax, i)
1036
+
1037
+ ax.get_yaxis().set_visible(True)
1038
+ return ax
1039
+
1040
+ @final
1041
+ def on_right(self, i: int):
1042
+ if isinstance(self.secondary_y, bool):
1043
+ return self.secondary_y
1044
+
1045
+ if isinstance(self.secondary_y, (tuple, list, np.ndarray, ABCIndex)):
1046
+ return self.data.columns[i] in self.secondary_y
1047
+
1048
+ @final
1049
+ def _apply_style_colors(
1050
+ self, colors, kwds: dict[str, Any], col_num: int, label: str
1051
+ ):
1052
+ """
1053
+ Manage style and color based on column number and its label.
1054
+ Returns tuple of appropriate style and kwds which "color" may be added.
1055
+ """
1056
+ style = None
1057
+ if self.style is not None:
1058
+ if isinstance(self.style, list):
1059
+ try:
1060
+ style = self.style[col_num]
1061
+ except IndexError:
1062
+ pass
1063
+ elif isinstance(self.style, dict):
1064
+ style = self.style.get(label, style)
1065
+ else:
1066
+ style = self.style
1067
+
1068
+ has_color = "color" in kwds or self.colormap is not None
1069
+ nocolor_style = style is None or not _color_in_style(style)
1070
+ if (has_color or self.subplots) and nocolor_style:
1071
+ if isinstance(colors, dict):
1072
+ kwds["color"] = colors[label]
1073
+ else:
1074
+ kwds["color"] = colors[col_num % len(colors)]
1075
+ return style, kwds
1076
+
1077
+ def _get_colors(
1078
+ self,
1079
+ num_colors: int | None = None,
1080
+ color_kwds: str = "color",
1081
+ ):
1082
+ if num_colors is None:
1083
+ num_colors = self.nseries
1084
+ if color_kwds == "color":
1085
+ color = self.color
1086
+ else:
1087
+ color = self.kwds.get(color_kwds)
1088
+ return get_standard_colors(
1089
+ num_colors=num_colors,
1090
+ colormap=self.colormap,
1091
+ color=color,
1092
+ )
1093
+
1094
+ # TODO: tighter typing for first return?
1095
+ @final
1096
+ @staticmethod
1097
+ def _parse_errorbars(
1098
+ label: str, err, data: NDFrameT, nseries: int
1099
+ ) -> tuple[Any, NDFrameT]:
1100
+ """
1101
+ Look for error keyword arguments and return the actual errorbar data
1102
+ or return the error DataFrame/dict
1103
+
1104
+ Error bars can be specified in several ways:
1105
+ Series: the user provides a pandas.Series object of the same
1106
+ length as the data
1107
+ ndarray: provides a np.ndarray of the same length as the data
1108
+ DataFrame/dict: error values are paired with keys matching the
1109
+ key in the plotted DataFrame
1110
+ str: the name of the column within the plotted DataFrame
1111
+
1112
+ Asymmetrical error bars are also supported, however raw error values
1113
+ must be provided in this case. For a ``N`` length :class:`Series`, a
1114
+ ``2xN`` array should be provided indicating lower and upper (or left
1115
+ and right) errors. For a ``MxN`` :class:`DataFrame`, asymmetrical errors
1116
+ should be in a ``Mx2xN`` array.
1117
+ """
1118
+ if err is None:
1119
+ return None, data
1120
+
1121
+ def match_labels(data, e):
1122
+ e = e.reindex(data.index)
1123
+ return e
1124
+
1125
+ # key-matched DataFrame
1126
+ if isinstance(err, ABCDataFrame):
1127
+ err = match_labels(data, err)
1128
+ # key-matched dict
1129
+ elif isinstance(err, dict):
1130
+ pass
1131
+
1132
+ # Series of error values
1133
+ elif isinstance(err, ABCSeries):
1134
+ # broadcast error series across data
1135
+ err = match_labels(data, err)
1136
+ err = np.atleast_2d(err)
1137
+ err = np.tile(err, (nseries, 1))
1138
+
1139
+ # errors are a column in the dataframe
1140
+ elif isinstance(err, str):
1141
+ evalues = data[err].values
1142
+ data = data[data.columns.drop(err)]
1143
+ err = np.atleast_2d(evalues)
1144
+ err = np.tile(err, (nseries, 1))
1145
+
1146
+ elif is_list_like(err):
1147
+ if is_iterator(err):
1148
+ err = np.atleast_2d(list(err))
1149
+ else:
1150
+ # raw error values
1151
+ err = np.atleast_2d(err)
1152
+
1153
+ err_shape = err.shape
1154
+
1155
+ # asymmetrical error bars
1156
+ if isinstance(data, ABCSeries) and err_shape[0] == 2:
1157
+ err = np.expand_dims(err, 0)
1158
+ err_shape = err.shape
1159
+ if err_shape[2] != len(data):
1160
+ raise ValueError(
1161
+ "Asymmetrical error bars should be provided "
1162
+ f"with the shape (2, {len(data)})"
1163
+ )
1164
+ elif isinstance(data, ABCDataFrame) and err.ndim == 3:
1165
+ if (
1166
+ (err_shape[0] != nseries)
1167
+ or (err_shape[1] != 2)
1168
+ or (err_shape[2] != len(data))
1169
+ ):
1170
+ raise ValueError(
1171
+ "Asymmetrical error bars should be provided "
1172
+ f"with the shape ({nseries}, 2, {len(data)})"
1173
+ )
1174
+
1175
+ # broadcast errors to each data series
1176
+ if len(err) == 1:
1177
+ err = np.tile(err, (nseries, 1))
1178
+
1179
+ elif is_number(err):
1180
+ err = np.tile(
1181
+ [err],
1182
+ (nseries, len(data)),
1183
+ )
1184
+
1185
+ else:
1186
+ msg = f"No valid {label} detected"
1187
+ raise ValueError(msg)
1188
+
1189
+ return err, data
1190
+
1191
+ @final
1192
+ def _get_errorbars(
1193
+ self, label=None, index=None, xerr: bool = True, yerr: bool = True
1194
+ ) -> dict[str, Any]:
1195
+ errors = {}
1196
+
1197
+ for kw, flag in zip(["xerr", "yerr"], [xerr, yerr]):
1198
+ if flag:
1199
+ err = self.errors[kw]
1200
+ # user provided label-matched dataframe of errors
1201
+ if isinstance(err, (ABCDataFrame, dict)):
1202
+ if label is not None and label in err.keys():
1203
+ err = err[label]
1204
+ else:
1205
+ err = None
1206
+ elif index is not None and err is not None:
1207
+ err = err[index]
1208
+
1209
+ if err is not None:
1210
+ errors[kw] = err
1211
+ return errors
1212
+
1213
+ @final
1214
+ def _get_subplots(self, fig: Figure):
1215
+ if Version(mpl.__version__) < Version("3.8"):
1216
+ from matplotlib.axes import Subplot as Klass
1217
+ else:
1218
+ from matplotlib.axes import Axes as Klass
1219
+
1220
+ return [
1221
+ ax
1222
+ for ax in fig.get_axes()
1223
+ if (isinstance(ax, Klass) and ax.get_subplotspec() is not None)
1224
+ ]
1225
+
1226
+ @final
1227
+ def _get_axes_layout(self, fig: Figure) -> tuple[int, int]:
1228
+ axes = self._get_subplots(fig)
1229
+ x_set = set()
1230
+ y_set = set()
1231
+ for ax in axes:
1232
+ # check axes coordinates to estimate layout
1233
+ points = ax.get_position().get_points()
1234
+ x_set.add(points[0][0])
1235
+ y_set.add(points[0][1])
1236
+ return (len(y_set), len(x_set))
1237
+
1238
+
1239
+ class PlanePlot(MPLPlot, ABC):
1240
+ """
1241
+ Abstract class for plotting on plane, currently scatter and hexbin.
1242
+ """
1243
+
1244
+ _layout_type = "single"
1245
+
1246
+ def __init__(self, data, x, y, **kwargs) -> None:
1247
+ MPLPlot.__init__(self, data, **kwargs)
1248
+ if x is None or y is None:
1249
+ raise ValueError(self._kind + " requires an x and y column")
1250
+ if is_integer(x) and not self.data.columns._holds_integer():
1251
+ x = self.data.columns[x]
1252
+ if is_integer(y) and not self.data.columns._holds_integer():
1253
+ y = self.data.columns[y]
1254
+
1255
+ self.x = x
1256
+ self.y = y
1257
+
1258
+ @final
1259
+ def _get_nseries(self, data: Series | DataFrame) -> int:
1260
+ return 1
1261
+
1262
+ @final
1263
+ def _post_plot_logic(self, ax: Axes, data) -> None:
1264
+ x, y = self.x, self.y
1265
+ xlabel = self.xlabel if self.xlabel is not None else pprint_thing(x)
1266
+ ylabel = self.ylabel if self.ylabel is not None else pprint_thing(y)
1267
+ # error: Argument 1 to "set_xlabel" of "_AxesBase" has incompatible
1268
+ # type "Hashable"; expected "str"
1269
+ ax.set_xlabel(xlabel) # type: ignore[arg-type]
1270
+ ax.set_ylabel(ylabel) # type: ignore[arg-type]
1271
+
1272
+ @final
1273
+ def _plot_colorbar(self, ax: Axes, *, fig: Figure, **kwds):
1274
+ # Addresses issues #10611 and #10678:
1275
+ # When plotting scatterplots and hexbinplots in IPython
1276
+ # inline backend the colorbar axis height tends not to
1277
+ # exactly match the parent axis height.
1278
+ # The difference is due to small fractional differences
1279
+ # in floating points with similar representation.
1280
+ # To deal with this, this method forces the colorbar
1281
+ # height to take the height of the parent axes.
1282
+ # For a more detailed description of the issue
1283
+ # see the following link:
1284
+ # https://github.com/ipython/ipython/issues/11215
1285
+
1286
+ # GH33389, if ax is used multiple times, we should always
1287
+ # use the last one which contains the latest information
1288
+ # about the ax
1289
+ img = ax.collections[-1]
1290
+ return fig.colorbar(img, ax=ax, **kwds)
1291
+
1292
+
1293
+ class ScatterPlot(PlanePlot):
1294
+ @property
1295
+ def _kind(self) -> Literal["scatter"]:
1296
+ return "scatter"
1297
+
1298
+ def __init__(
1299
+ self,
1300
+ data,
1301
+ x,
1302
+ y,
1303
+ s=None,
1304
+ c=None,
1305
+ *,
1306
+ colorbar: bool | lib.NoDefault = lib.no_default,
1307
+ norm=None,
1308
+ **kwargs,
1309
+ ) -> None:
1310
+ if s is None:
1311
+ # hide the matplotlib default for size, in case we want to change
1312
+ # the handling of this argument later
1313
+ s = 20
1314
+ elif is_hashable(s) and s in data.columns:
1315
+ s = data[s]
1316
+ self.s = s
1317
+
1318
+ self.colorbar = colorbar
1319
+ self.norm = norm
1320
+
1321
+ super().__init__(data, x, y, **kwargs)
1322
+ if is_integer(c) and not self.data.columns._holds_integer():
1323
+ c = self.data.columns[c]
1324
+ self.c = c
1325
+
1326
+ def _make_plot(self, fig: Figure) -> None:
1327
+ x, y, c, data = self.x, self.y, self.c, self.data
1328
+ ax = self.axes[0]
1329
+
1330
+ c_is_column = is_hashable(c) and c in self.data.columns
1331
+
1332
+ color_by_categorical = c_is_column and isinstance(
1333
+ self.data[c].dtype, CategoricalDtype
1334
+ )
1335
+
1336
+ color = self.color
1337
+ c_values = self._get_c_values(color, color_by_categorical, c_is_column)
1338
+ norm, cmap = self._get_norm_and_cmap(c_values, color_by_categorical)
1339
+ cb = self._get_colorbar(c_values, c_is_column)
1340
+
1341
+ if self.legend:
1342
+ label = self.label
1343
+ else:
1344
+ label = None
1345
+ scatter = ax.scatter(
1346
+ data[x].values,
1347
+ data[y].values,
1348
+ c=c_values,
1349
+ label=label,
1350
+ cmap=cmap,
1351
+ norm=norm,
1352
+ s=self.s,
1353
+ **self.kwds,
1354
+ )
1355
+ if cb:
1356
+ cbar_label = c if c_is_column else ""
1357
+ cbar = self._plot_colorbar(ax, fig=fig, label=cbar_label)
1358
+ if color_by_categorical:
1359
+ n_cats = len(self.data[c].cat.categories)
1360
+ cbar.set_ticks(np.linspace(0.5, n_cats - 0.5, n_cats))
1361
+ cbar.ax.set_yticklabels(self.data[c].cat.categories)
1362
+
1363
+ if label is not None:
1364
+ self._append_legend_handles_labels(
1365
+ # error: Argument 2 to "_append_legend_handles_labels" of
1366
+ # "MPLPlot" has incompatible type "Hashable"; expected "str"
1367
+ scatter,
1368
+ label, # type: ignore[arg-type]
1369
+ )
1370
+
1371
+ errors_x = self._get_errorbars(label=x, index=0, yerr=False)
1372
+ errors_y = self._get_errorbars(label=y, index=0, xerr=False)
1373
+ if len(errors_x) > 0 or len(errors_y) > 0:
1374
+ err_kwds = dict(errors_x, **errors_y)
1375
+ err_kwds["ecolor"] = scatter.get_facecolor()[0]
1376
+ ax.errorbar(data[x].values, data[y].values, linestyle="none", **err_kwds)
1377
+
1378
+ def _get_c_values(self, color, color_by_categorical: bool, c_is_column: bool):
1379
+ c = self.c
1380
+ if c is not None and color is not None:
1381
+ raise TypeError("Specify exactly one of `c` and `color`")
1382
+ if c is None and color is None:
1383
+ c_values = self.plt.rcParams["patch.facecolor"]
1384
+ elif color is not None:
1385
+ c_values = color
1386
+ elif color_by_categorical:
1387
+ c_values = self.data[c].cat.codes
1388
+ elif c_is_column:
1389
+ c_values = self.data[c].values
1390
+ else:
1391
+ c_values = c
1392
+ return c_values
1393
+
1394
+ def _get_norm_and_cmap(self, c_values, color_by_categorical: bool):
1395
+ c = self.c
1396
+ if self.colormap is not None:
1397
+ cmap = mpl.colormaps.get_cmap(self.colormap)
1398
+ # cmap is only used if c_values are integers, otherwise UserWarning.
1399
+ # GH-53908: additionally call isinstance() because is_integer_dtype
1400
+ # returns True for "b" (meaning "blue" and not int8 in this context)
1401
+ elif not isinstance(c_values, str) and is_integer_dtype(c_values):
1402
+ # pandas uses colormap, matplotlib uses cmap.
1403
+ cmap = mpl.colormaps["Greys"]
1404
+ else:
1405
+ cmap = None
1406
+
1407
+ if color_by_categorical and cmap is not None:
1408
+ from matplotlib import colors
1409
+
1410
+ n_cats = len(self.data[c].cat.categories)
1411
+ cmap = colors.ListedColormap([cmap(i) for i in range(cmap.N)])
1412
+ bounds = np.linspace(0, n_cats, n_cats + 1)
1413
+ norm = colors.BoundaryNorm(bounds, cmap.N)
1414
+ # TODO: warn that we are ignoring self.norm if user specified it?
1415
+ # Doesn't happen in any tests 2023-11-09
1416
+ else:
1417
+ norm = self.norm
1418
+ return norm, cmap
1419
+
1420
+ def _get_colorbar(self, c_values, c_is_column: bool) -> bool:
1421
+ # plot colorbar if
1422
+ # 1. colormap is assigned, and
1423
+ # 2.`c` is a column containing only numeric values
1424
+ plot_colorbar = self.colormap or c_is_column
1425
+ cb = self.colorbar
1426
+ if cb is lib.no_default:
1427
+ return is_numeric_dtype(c_values) and plot_colorbar
1428
+ return cb
1429
+
1430
+
1431
+ class HexBinPlot(PlanePlot):
1432
+ @property
1433
+ def _kind(self) -> Literal["hexbin"]:
1434
+ return "hexbin"
1435
+
1436
+ def __init__(self, data, x, y, C=None, *, colorbar: bool = True, **kwargs) -> None:
1437
+ super().__init__(data, x, y, **kwargs)
1438
+ if is_integer(C) and not self.data.columns._holds_integer():
1439
+ C = self.data.columns[C]
1440
+ self.C = C
1441
+
1442
+ self.colorbar = colorbar
1443
+
1444
+ # Scatter plot allows to plot objects data
1445
+ if len(self.data[self.x]._get_numeric_data()) == 0:
1446
+ raise ValueError(self._kind + " requires x column to be numeric")
1447
+ if len(self.data[self.y]._get_numeric_data()) == 0:
1448
+ raise ValueError(self._kind + " requires y column to be numeric")
1449
+
1450
+ def _make_plot(self, fig: Figure) -> None:
1451
+ x, y, data, C = self.x, self.y, self.data, self.C
1452
+ ax = self.axes[0]
1453
+ # pandas uses colormap, matplotlib uses cmap.
1454
+ cmap = self.colormap or "BuGn"
1455
+ cmap = mpl.colormaps.get_cmap(cmap)
1456
+ cb = self.colorbar
1457
+
1458
+ if C is None:
1459
+ c_values = None
1460
+ else:
1461
+ c_values = data[C].values
1462
+
1463
+ ax.hexbin(data[x].values, data[y].values, C=c_values, cmap=cmap, **self.kwds)
1464
+ if cb:
1465
+ self._plot_colorbar(ax, fig=fig)
1466
+
1467
+ def _make_legend(self) -> None:
1468
+ pass
1469
+
1470
+
1471
+ class LinePlot(MPLPlot):
1472
+ _default_rot = 0
1473
+
1474
+ @property
1475
+ def orientation(self) -> PlottingOrientation:
1476
+ return "vertical"
1477
+
1478
+ @property
1479
+ def _kind(self) -> Literal["line", "area", "hist", "kde", "box"]:
1480
+ return "line"
1481
+
1482
+ def __init__(self, data, **kwargs) -> None:
1483
+ from pandas.plotting import plot_params
1484
+
1485
+ MPLPlot.__init__(self, data, **kwargs)
1486
+ if self.stacked:
1487
+ self.data = self.data.fillna(value=0)
1488
+ self.x_compat = plot_params["x_compat"]
1489
+ if "x_compat" in self.kwds:
1490
+ self.x_compat = bool(self.kwds.pop("x_compat"))
1491
+
1492
+ @final
1493
+ def _is_ts_plot(self) -> bool:
1494
+ # this is slightly deceptive
1495
+ return not self.x_compat and self.use_index and self._use_dynamic_x()
1496
+
1497
+ @final
1498
+ def _use_dynamic_x(self) -> bool:
1499
+ return use_dynamic_x(self._get_ax(0), self.data)
1500
+
1501
+ def _make_plot(self, fig: Figure) -> None:
1502
+ if self._is_ts_plot():
1503
+ data = maybe_convert_index(self._get_ax(0), self.data)
1504
+
1505
+ x = data.index # dummy, not used
1506
+ plotf = self._ts_plot
1507
+ it = data.items()
1508
+ else:
1509
+ x = self._get_xticks()
1510
+ # error: Incompatible types in assignment (expression has type
1511
+ # "Callable[[Any, Any, Any, Any, Any, Any, KwArg(Any)], Any]", variable has
1512
+ # type "Callable[[Any, Any, Any, Any, KwArg(Any)], Any]")
1513
+ plotf = self._plot # type: ignore[assignment]
1514
+ # error: Incompatible types in assignment (expression has type
1515
+ # "Iterator[tuple[Hashable, ndarray[Any, Any]]]", variable has
1516
+ # type "Iterable[tuple[Hashable, Series]]")
1517
+ it = self._iter_data(data=self.data) # type: ignore[assignment]
1518
+
1519
+ stacking_id = self._get_stacking_id()
1520
+ is_errorbar = com.any_not_none(*self.errors.values())
1521
+
1522
+ colors = self._get_colors()
1523
+ for i, (label, y) in enumerate(it):
1524
+ ax = self._get_ax(i)
1525
+ kwds = self.kwds.copy()
1526
+ if self.color is not None:
1527
+ kwds["color"] = self.color
1528
+ style, kwds = self._apply_style_colors(
1529
+ colors,
1530
+ kwds,
1531
+ i,
1532
+ # error: Argument 4 to "_apply_style_colors" of "MPLPlot" has
1533
+ # incompatible type "Hashable"; expected "str"
1534
+ label, # type: ignore[arg-type]
1535
+ )
1536
+
1537
+ errors = self._get_errorbars(label=label, index=i)
1538
+ kwds = dict(kwds, **errors)
1539
+
1540
+ label = pprint_thing(label)
1541
+ label = self._mark_right_label(label, index=i)
1542
+ kwds["label"] = label
1543
+
1544
+ newlines = plotf(
1545
+ ax,
1546
+ x,
1547
+ y,
1548
+ style=style,
1549
+ column_num=i,
1550
+ stacking_id=stacking_id,
1551
+ is_errorbar=is_errorbar,
1552
+ **kwds,
1553
+ )
1554
+ self._append_legend_handles_labels(newlines[0], label)
1555
+
1556
+ if self._is_ts_plot():
1557
+ # reset of xlim should be used for ts data
1558
+ # TODO: GH28021, should find a way to change view limit on xaxis
1559
+ lines = get_all_lines(ax)
1560
+ left, right = get_xlim(lines)
1561
+ ax.set_xlim(left, right)
1562
+
1563
+ # error: Signature of "_plot" incompatible with supertype "MPLPlot"
1564
+ @classmethod
1565
+ def _plot( # type: ignore[override]
1566
+ cls,
1567
+ ax: Axes,
1568
+ x,
1569
+ y: np.ndarray,
1570
+ style=None,
1571
+ column_num=None,
1572
+ stacking_id=None,
1573
+ **kwds,
1574
+ ):
1575
+ # column_num is used to get the target column from plotf in line and
1576
+ # area plots
1577
+ if column_num == 0:
1578
+ cls._initialize_stacker(ax, stacking_id, len(y))
1579
+ y_values = cls._get_stacked_values(ax, stacking_id, y, kwds["label"])
1580
+ lines = MPLPlot._plot(ax, x, y_values, style=style, **kwds)
1581
+ cls._update_stacker(ax, stacking_id, y)
1582
+ return lines
1583
+
1584
+ @final
1585
+ def _ts_plot(self, ax: Axes, x, data: Series, style=None, **kwds):
1586
+ # accept x to be consistent with normal plot func,
1587
+ # x is not passed to tsplot as it uses data.index as x coordinate
1588
+ # column_num must be in kwds for stacking purpose
1589
+ freq, data = maybe_resample(data, ax, kwds)
1590
+
1591
+ # Set ax with freq info
1592
+ decorate_axes(ax, freq)
1593
+ # digging deeper
1594
+ if hasattr(ax, "left_ax"):
1595
+ decorate_axes(ax.left_ax, freq)
1596
+ if hasattr(ax, "right_ax"):
1597
+ decorate_axes(ax.right_ax, freq)
1598
+ # TODO #54485
1599
+ ax._plot_data.append((data, self._kind, kwds)) # type: ignore[attr-defined]
1600
+
1601
+ lines = self._plot(ax, data.index, np.asarray(data.values), style=style, **kwds)
1602
+ # set date formatter, locators and rescale limits
1603
+ # TODO #54485
1604
+ format_dateaxis(ax, ax.freq, data.index) # type: ignore[arg-type, attr-defined]
1605
+ return lines
1606
+
1607
+ @final
1608
+ def _get_stacking_id(self) -> int | None:
1609
+ if self.stacked:
1610
+ return id(self.data)
1611
+ else:
1612
+ return None
1613
+
1614
+ @final
1615
+ @classmethod
1616
+ def _initialize_stacker(cls, ax: Axes, stacking_id, n: int) -> None:
1617
+ if stacking_id is None:
1618
+ return
1619
+ if not hasattr(ax, "_stacker_pos_prior"):
1620
+ # TODO #54485
1621
+ ax._stacker_pos_prior = {} # type: ignore[attr-defined]
1622
+ if not hasattr(ax, "_stacker_neg_prior"):
1623
+ # TODO #54485
1624
+ ax._stacker_neg_prior = {} # type: ignore[attr-defined]
1625
+ # TODO #54485
1626
+ ax._stacker_pos_prior[stacking_id] = np.zeros(n) # type: ignore[attr-defined]
1627
+ # TODO #54485
1628
+ ax._stacker_neg_prior[stacking_id] = np.zeros(n) # type: ignore[attr-defined]
1629
+
1630
+ @final
1631
+ @classmethod
1632
+ def _get_stacked_values(
1633
+ cls, ax: Axes, stacking_id: int | None, values: np.ndarray, label
1634
+ ) -> np.ndarray:
1635
+ if stacking_id is None:
1636
+ return values
1637
+ if not hasattr(ax, "_stacker_pos_prior"):
1638
+ # stacker may not be initialized for subplots
1639
+ cls._initialize_stacker(ax, stacking_id, len(values))
1640
+
1641
+ if (values >= 0).all():
1642
+ # TODO #54485
1643
+ return (
1644
+ ax._stacker_pos_prior[stacking_id] # type: ignore[attr-defined]
1645
+ + values
1646
+ )
1647
+ elif (values <= 0).all():
1648
+ # TODO #54485
1649
+ return (
1650
+ ax._stacker_neg_prior[stacking_id] # type: ignore[attr-defined]
1651
+ + values
1652
+ )
1653
+
1654
+ raise ValueError(
1655
+ "When stacked is True, each column must be either "
1656
+ "all positive or all negative. "
1657
+ f"Column '{label}' contains both positive and negative values"
1658
+ )
1659
+
1660
+ @final
1661
+ @classmethod
1662
+ def _update_stacker(cls, ax: Axes, stacking_id: int | None, values) -> None:
1663
+ if stacking_id is None:
1664
+ return
1665
+ if (values >= 0).all():
1666
+ # TODO #54485
1667
+ ax._stacker_pos_prior[stacking_id] += values # type: ignore[attr-defined]
1668
+ elif (values <= 0).all():
1669
+ # TODO #54485
1670
+ ax._stacker_neg_prior[stacking_id] += values # type: ignore[attr-defined]
1671
+
1672
+ def _post_plot_logic(self, ax: Axes, data) -> None:
1673
+ from matplotlib.ticker import FixedLocator
1674
+
1675
+ def get_label(i):
1676
+ if is_float(i) and i.is_integer():
1677
+ i = int(i)
1678
+ try:
1679
+ return pprint_thing(data.index[i])
1680
+ except Exception:
1681
+ return ""
1682
+
1683
+ if self._need_to_set_index:
1684
+ xticks = ax.get_xticks()
1685
+ xticklabels = [get_label(x) for x in xticks]
1686
+ # error: Argument 1 to "FixedLocator" has incompatible type "ndarray[Any,
1687
+ # Any]"; expected "Sequence[float]"
1688
+ ax.xaxis.set_major_locator(FixedLocator(xticks)) # type: ignore[arg-type]
1689
+ ax.set_xticklabels(xticklabels)
1690
+
1691
+ # If the index is an irregular time series, then by default
1692
+ # we rotate the tick labels. The exception is if there are
1693
+ # subplots which don't share their x-axes, in which we case
1694
+ # we don't rotate the ticklabels as by default the subplots
1695
+ # would be too close together.
1696
+ condition = (
1697
+ not self._use_dynamic_x()
1698
+ and (data.index._is_all_dates and self.use_index)
1699
+ and (not self.subplots or (self.subplots and self.sharex))
1700
+ )
1701
+
1702
+ index_name = self._get_index_name()
1703
+
1704
+ if condition:
1705
+ # irregular TS rotated 30 deg. by default
1706
+ # probably a better place to check / set this.
1707
+ if not self._rot_set:
1708
+ self.rot = 30
1709
+ format_date_labels(ax, rot=self.rot)
1710
+
1711
+ if index_name is not None and self.use_index:
1712
+ ax.set_xlabel(index_name)
1713
+
1714
+
1715
+ class AreaPlot(LinePlot):
1716
+ @property
1717
+ def _kind(self) -> Literal["area"]:
1718
+ return "area"
1719
+
1720
+ def __init__(self, data, **kwargs) -> None:
1721
+ kwargs.setdefault("stacked", True)
1722
+ with warnings.catch_warnings():
1723
+ warnings.filterwarnings(
1724
+ "ignore",
1725
+ "Downcasting object dtype arrays",
1726
+ category=FutureWarning,
1727
+ )
1728
+ data = data.fillna(value=0)
1729
+ LinePlot.__init__(self, data, **kwargs)
1730
+
1731
+ if not self.stacked:
1732
+ # use smaller alpha to distinguish overlap
1733
+ self.kwds.setdefault("alpha", 0.5)
1734
+
1735
+ if self.logy or self.loglog:
1736
+ raise ValueError("Log-y scales are not supported in area plot")
1737
+
1738
+ # error: Signature of "_plot" incompatible with supertype "MPLPlot"
1739
+ @classmethod
1740
+ def _plot( # type: ignore[override]
1741
+ cls,
1742
+ ax: Axes,
1743
+ x,
1744
+ y: np.ndarray,
1745
+ style=None,
1746
+ column_num=None,
1747
+ stacking_id=None,
1748
+ is_errorbar: bool = False,
1749
+ **kwds,
1750
+ ):
1751
+ if column_num == 0:
1752
+ cls._initialize_stacker(ax, stacking_id, len(y))
1753
+ y_values = cls._get_stacked_values(ax, stacking_id, y, kwds["label"])
1754
+
1755
+ # need to remove label, because subplots uses mpl legend as it is
1756
+ line_kwds = kwds.copy()
1757
+ line_kwds.pop("label")
1758
+ lines = MPLPlot._plot(ax, x, y_values, style=style, **line_kwds)
1759
+
1760
+ # get data from the line to get coordinates for fill_between
1761
+ xdata, y_values = lines[0].get_data(orig=False)
1762
+
1763
+ # unable to use ``_get_stacked_values`` here to get starting point
1764
+ if stacking_id is None:
1765
+ start = np.zeros(len(y))
1766
+ elif (y >= 0).all():
1767
+ # TODO #54485
1768
+ start = ax._stacker_pos_prior[stacking_id] # type: ignore[attr-defined]
1769
+ elif (y <= 0).all():
1770
+ # TODO #54485
1771
+ start = ax._stacker_neg_prior[stacking_id] # type: ignore[attr-defined]
1772
+ else:
1773
+ start = np.zeros(len(y))
1774
+
1775
+ if "color" not in kwds:
1776
+ kwds["color"] = lines[0].get_color()
1777
+
1778
+ rect = ax.fill_between(xdata, start, y_values, **kwds)
1779
+ cls._update_stacker(ax, stacking_id, y)
1780
+
1781
+ # LinePlot expects list of artists
1782
+ res = [rect]
1783
+ return res
1784
+
1785
+ def _post_plot_logic(self, ax: Axes, data) -> None:
1786
+ LinePlot._post_plot_logic(self, ax, data)
1787
+
1788
+ is_shared_y = len(list(ax.get_shared_y_axes())) > 0
1789
+ # do not override the default axis behaviour in case of shared y axes
1790
+ if self.ylim is None and not is_shared_y:
1791
+ if (data >= 0).all().all():
1792
+ ax.set_ylim(0, None)
1793
+ elif (data <= 0).all().all():
1794
+ ax.set_ylim(None, 0)
1795
+
1796
+
1797
+ class BarPlot(MPLPlot):
1798
+ @property
1799
+ def _kind(self) -> Literal["bar", "barh"]:
1800
+ return "bar"
1801
+
1802
+ _default_rot = 90
1803
+
1804
+ @property
1805
+ def orientation(self) -> PlottingOrientation:
1806
+ return "vertical"
1807
+
1808
+ def __init__(
1809
+ self,
1810
+ data,
1811
+ *,
1812
+ align="center",
1813
+ bottom=0,
1814
+ left=0,
1815
+ width=0.5,
1816
+ position=0.5,
1817
+ log=False,
1818
+ **kwargs,
1819
+ ) -> None:
1820
+ # we have to treat a series differently than a
1821
+ # 1-column DataFrame w.r.t. color handling
1822
+ self._is_series = isinstance(data, ABCSeries)
1823
+ self.bar_width = width
1824
+ self._align = align
1825
+ self._position = position
1826
+ self.tick_pos = np.arange(len(data))
1827
+
1828
+ if is_list_like(bottom):
1829
+ bottom = np.array(bottom)
1830
+ if is_list_like(left):
1831
+ left = np.array(left)
1832
+ self.bottom = bottom
1833
+ self.left = left
1834
+
1835
+ self.log = log
1836
+
1837
+ MPLPlot.__init__(self, data, **kwargs)
1838
+
1839
+ @cache_readonly
1840
+ def ax_pos(self) -> np.ndarray:
1841
+ return self.tick_pos - self.tickoffset
1842
+
1843
+ @cache_readonly
1844
+ def tickoffset(self):
1845
+ if self.stacked or self.subplots:
1846
+ return self.bar_width * self._position
1847
+ elif self._align == "edge":
1848
+ w = self.bar_width / self.nseries
1849
+ return self.bar_width * (self._position - 0.5) + w * 0.5
1850
+ else:
1851
+ return self.bar_width * self._position
1852
+
1853
+ @cache_readonly
1854
+ def lim_offset(self):
1855
+ if self.stacked or self.subplots:
1856
+ if self._align == "edge":
1857
+ return self.bar_width / 2
1858
+ else:
1859
+ return 0
1860
+ elif self._align == "edge":
1861
+ w = self.bar_width / self.nseries
1862
+ return w * 0.5
1863
+ else:
1864
+ return 0
1865
+
1866
+ # error: Signature of "_plot" incompatible with supertype "MPLPlot"
1867
+ @classmethod
1868
+ def _plot( # type: ignore[override]
1869
+ cls,
1870
+ ax: Axes,
1871
+ x,
1872
+ y: np.ndarray,
1873
+ w,
1874
+ start: int | npt.NDArray[np.intp] = 0,
1875
+ log: bool = False,
1876
+ **kwds,
1877
+ ):
1878
+ return ax.bar(x, y, w, bottom=start, log=log, **kwds)
1879
+
1880
+ @property
1881
+ def _start_base(self):
1882
+ return self.bottom
1883
+
1884
+ def _make_plot(self, fig: Figure) -> None:
1885
+ colors = self._get_colors()
1886
+ ncolors = len(colors)
1887
+
1888
+ pos_prior = neg_prior = np.zeros(len(self.data))
1889
+ K = self.nseries
1890
+
1891
+ data = self.data.fillna(0)
1892
+ for i, (label, y) in enumerate(self._iter_data(data=data)):
1893
+ ax = self._get_ax(i)
1894
+ kwds = self.kwds.copy()
1895
+ if self._is_series:
1896
+ kwds["color"] = colors
1897
+ elif isinstance(colors, dict):
1898
+ kwds["color"] = colors[label]
1899
+ else:
1900
+ kwds["color"] = colors[i % ncolors]
1901
+
1902
+ errors = self._get_errorbars(label=label, index=i)
1903
+ kwds = dict(kwds, **errors)
1904
+
1905
+ label = pprint_thing(label)
1906
+ label = self._mark_right_label(label, index=i)
1907
+
1908
+ if (("yerr" in kwds) or ("xerr" in kwds)) and (kwds.get("ecolor") is None):
1909
+ kwds["ecolor"] = mpl.rcParams["xtick.color"]
1910
+
1911
+ start = 0
1912
+ if self.log and (y >= 1).all():
1913
+ start = 1
1914
+ start = start + self._start_base
1915
+
1916
+ kwds["align"] = self._align
1917
+ if self.subplots:
1918
+ w = self.bar_width / 2
1919
+ rect = self._plot(
1920
+ ax,
1921
+ self.ax_pos + w,
1922
+ y,
1923
+ self.bar_width,
1924
+ start=start,
1925
+ label=label,
1926
+ log=self.log,
1927
+ **kwds,
1928
+ )
1929
+ ax.set_title(label)
1930
+ elif self.stacked:
1931
+ mask = y > 0
1932
+ start = np.where(mask, pos_prior, neg_prior) + self._start_base
1933
+ w = self.bar_width / 2
1934
+ rect = self._plot(
1935
+ ax,
1936
+ self.ax_pos + w,
1937
+ y,
1938
+ self.bar_width,
1939
+ start=start,
1940
+ label=label,
1941
+ log=self.log,
1942
+ **kwds,
1943
+ )
1944
+ pos_prior = pos_prior + np.where(mask, y, 0)
1945
+ neg_prior = neg_prior + np.where(mask, 0, y)
1946
+ else:
1947
+ w = self.bar_width / K
1948
+ rect = self._plot(
1949
+ ax,
1950
+ self.ax_pos + (i + 0.5) * w,
1951
+ y,
1952
+ w,
1953
+ start=start,
1954
+ label=label,
1955
+ log=self.log,
1956
+ **kwds,
1957
+ )
1958
+ self._append_legend_handles_labels(rect, label)
1959
+
1960
+ def _post_plot_logic(self, ax: Axes, data) -> None:
1961
+ if self.use_index:
1962
+ str_index = [pprint_thing(key) for key in data.index]
1963
+ else:
1964
+ str_index = [pprint_thing(key) for key in range(data.shape[0])]
1965
+
1966
+ s_edge = self.ax_pos[0] - 0.25 + self.lim_offset
1967
+ e_edge = self.ax_pos[-1] + 0.25 + self.bar_width + self.lim_offset
1968
+
1969
+ self._decorate_ticks(ax, self._get_index_name(), str_index, s_edge, e_edge)
1970
+
1971
+ def _decorate_ticks(
1972
+ self,
1973
+ ax: Axes,
1974
+ name: str | None,
1975
+ ticklabels: list[str],
1976
+ start_edge: float,
1977
+ end_edge: float,
1978
+ ) -> None:
1979
+ ax.set_xlim((start_edge, end_edge))
1980
+
1981
+ if self.xticks is not None:
1982
+ ax.set_xticks(np.array(self.xticks))
1983
+ else:
1984
+ ax.set_xticks(self.tick_pos)
1985
+ ax.set_xticklabels(ticklabels)
1986
+
1987
+ if name is not None and self.use_index:
1988
+ ax.set_xlabel(name)
1989
+
1990
+
1991
+ class BarhPlot(BarPlot):
1992
+ @property
1993
+ def _kind(self) -> Literal["barh"]:
1994
+ return "barh"
1995
+
1996
+ _default_rot = 0
1997
+
1998
+ @property
1999
+ def orientation(self) -> Literal["horizontal"]:
2000
+ return "horizontal"
2001
+
2002
+ @property
2003
+ def _start_base(self):
2004
+ return self.left
2005
+
2006
+ # error: Signature of "_plot" incompatible with supertype "MPLPlot"
2007
+ @classmethod
2008
+ def _plot( # type: ignore[override]
2009
+ cls,
2010
+ ax: Axes,
2011
+ x,
2012
+ y: np.ndarray,
2013
+ w,
2014
+ start: int | npt.NDArray[np.intp] = 0,
2015
+ log: bool = False,
2016
+ **kwds,
2017
+ ):
2018
+ return ax.barh(x, y, w, left=start, log=log, **kwds)
2019
+
2020
+ def _get_custom_index_name(self):
2021
+ return self.ylabel
2022
+
2023
+ def _decorate_ticks(
2024
+ self,
2025
+ ax: Axes,
2026
+ name: str | None,
2027
+ ticklabels: list[str],
2028
+ start_edge: float,
2029
+ end_edge: float,
2030
+ ) -> None:
2031
+ # horizontal bars
2032
+ ax.set_ylim((start_edge, end_edge))
2033
+ ax.set_yticks(self.tick_pos)
2034
+ ax.set_yticklabels(ticklabels)
2035
+ if name is not None and self.use_index:
2036
+ ax.set_ylabel(name)
2037
+ # error: Argument 1 to "set_xlabel" of "_AxesBase" has incompatible type
2038
+ # "Hashable | None"; expected "str"
2039
+ ax.set_xlabel(self.xlabel) # type: ignore[arg-type]
2040
+
2041
+
2042
+ class PiePlot(MPLPlot):
2043
+ @property
2044
+ def _kind(self) -> Literal["pie"]:
2045
+ return "pie"
2046
+
2047
+ _layout_type = "horizontal"
2048
+
2049
+ def __init__(self, data, kind=None, **kwargs) -> None:
2050
+ data = data.fillna(value=0)
2051
+ if (data < 0).any().any():
2052
+ raise ValueError(f"{self._kind} plot doesn't allow negative values")
2053
+ MPLPlot.__init__(self, data, kind=kind, **kwargs)
2054
+
2055
+ @classmethod
2056
+ def _validate_log_kwd(
2057
+ cls,
2058
+ kwd: str,
2059
+ value: bool | None | Literal["sym"],
2060
+ ) -> bool | None | Literal["sym"]:
2061
+ super()._validate_log_kwd(kwd=kwd, value=value)
2062
+ if value is not False:
2063
+ warnings.warn(
2064
+ f"PiePlot ignores the '{kwd}' keyword",
2065
+ UserWarning,
2066
+ stacklevel=find_stack_level(),
2067
+ )
2068
+ return False
2069
+
2070
+ def _validate_color_args(self, color, colormap) -> None:
2071
+ # TODO: warn if color is passed and ignored?
2072
+ return None
2073
+
2074
+ def _make_plot(self, fig: Figure) -> None:
2075
+ colors = self._get_colors(num_colors=len(self.data), color_kwds="colors")
2076
+ self.kwds.setdefault("colors", colors)
2077
+
2078
+ for i, (label, y) in enumerate(self._iter_data(data=self.data)):
2079
+ ax = self._get_ax(i)
2080
+ if label is not None:
2081
+ label = pprint_thing(label)
2082
+ ax.set_ylabel(label)
2083
+
2084
+ kwds = self.kwds.copy()
2085
+
2086
+ def blank_labeler(label, value):
2087
+ if value == 0:
2088
+ return ""
2089
+ else:
2090
+ return label
2091
+
2092
+ idx = [pprint_thing(v) for v in self.data.index]
2093
+ labels = kwds.pop("labels", idx)
2094
+ # labels is used for each wedge's labels
2095
+ # Blank out labels for values of 0 so they don't overlap
2096
+ # with nonzero wedges
2097
+ if labels is not None:
2098
+ blabels = [blank_labeler(left, value) for left, value in zip(labels, y)]
2099
+ else:
2100
+ blabels = None
2101
+ results = ax.pie(y, labels=blabels, **kwds)
2102
+
2103
+ if kwds.get("autopct", None) is not None:
2104
+ patches, texts, autotexts = results
2105
+ else:
2106
+ patches, texts = results
2107
+ autotexts = []
2108
+
2109
+ if self.fontsize is not None:
2110
+ for t in texts + autotexts:
2111
+ t.set_fontsize(self.fontsize)
2112
+
2113
+ # leglabels is used for legend labels
2114
+ leglabels = labels if labels is not None else idx
2115
+ for _patch, _leglabel in zip(patches, leglabels):
2116
+ self._append_legend_handles_labels(_patch, _leglabel)
2117
+
2118
+ def _post_plot_logic(self, ax: Axes, data) -> None:
2119
+ pass
venv/lib/python3.10/site-packages/pandas/plotting/_matplotlib/groupby.py ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from typing import TYPE_CHECKING
4
+
5
+ import numpy as np
6
+
7
+ from pandas.core.dtypes.missing import remove_na_arraylike
8
+
9
+ from pandas import (
10
+ MultiIndex,
11
+ concat,
12
+ )
13
+
14
+ from pandas.plotting._matplotlib.misc import unpack_single_str_list
15
+
16
+ if TYPE_CHECKING:
17
+ from collections.abc import Hashable
18
+
19
+ from pandas._typing import IndexLabel
20
+
21
+ from pandas import (
22
+ DataFrame,
23
+ Series,
24
+ )
25
+
26
+
27
+ def create_iter_data_given_by(
28
+ data: DataFrame, kind: str = "hist"
29
+ ) -> dict[Hashable, DataFrame | Series]:
30
+ """
31
+ Create data for iteration given `by` is assigned or not, and it is only
32
+ used in both hist and boxplot.
33
+
34
+ If `by` is assigned, return a dictionary of DataFrames in which the key of
35
+ dictionary is the values in groups.
36
+ If `by` is not assigned, return input as is, and this preserves current
37
+ status of iter_data.
38
+
39
+ Parameters
40
+ ----------
41
+ data : reformatted grouped data from `_compute_plot_data` method.
42
+ kind : str, plot kind. This function is only used for `hist` and `box` plots.
43
+
44
+ Returns
45
+ -------
46
+ iter_data : DataFrame or Dictionary of DataFrames
47
+
48
+ Examples
49
+ --------
50
+ If `by` is assigned:
51
+
52
+ >>> import numpy as np
53
+ >>> tuples = [('h1', 'a'), ('h1', 'b'), ('h2', 'a'), ('h2', 'b')]
54
+ >>> mi = pd.MultiIndex.from_tuples(tuples)
55
+ >>> value = [[1, 3, np.nan, np.nan],
56
+ ... [3, 4, np.nan, np.nan], [np.nan, np.nan, 5, 6]]
57
+ >>> data = pd.DataFrame(value, columns=mi)
58
+ >>> create_iter_data_given_by(data)
59
+ {'h1': h1
60
+ a b
61
+ 0 1.0 3.0
62
+ 1 3.0 4.0
63
+ 2 NaN NaN, 'h2': h2
64
+ a b
65
+ 0 NaN NaN
66
+ 1 NaN NaN
67
+ 2 5.0 6.0}
68
+ """
69
+
70
+ # For `hist` plot, before transformation, the values in level 0 are values
71
+ # in groups and subplot titles, and later used for column subselection and
72
+ # iteration; For `box` plot, values in level 1 are column names to show,
73
+ # and are used for iteration and as subplots titles.
74
+ if kind == "hist":
75
+ level = 0
76
+ else:
77
+ level = 1
78
+
79
+ # Select sub-columns based on the value of level of MI, and if `by` is
80
+ # assigned, data must be a MI DataFrame
81
+ assert isinstance(data.columns, MultiIndex)
82
+ return {
83
+ col: data.loc[:, data.columns.get_level_values(level) == col]
84
+ for col in data.columns.levels[level]
85
+ }
86
+
87
+
88
+ def reconstruct_data_with_by(
89
+ data: DataFrame, by: IndexLabel, cols: IndexLabel
90
+ ) -> DataFrame:
91
+ """
92
+ Internal function to group data, and reassign multiindex column names onto the
93
+ result in order to let grouped data be used in _compute_plot_data method.
94
+
95
+ Parameters
96
+ ----------
97
+ data : Original DataFrame to plot
98
+ by : grouped `by` parameter selected by users
99
+ cols : columns of data set (excluding columns used in `by`)
100
+
101
+ Returns
102
+ -------
103
+ Output is the reconstructed DataFrame with MultiIndex columns. The first level
104
+ of MI is unique values of groups, and second level of MI is the columns
105
+ selected by users.
106
+
107
+ Examples
108
+ --------
109
+ >>> d = {'h': ['h1', 'h1', 'h2'], 'a': [1, 3, 5], 'b': [3, 4, 6]}
110
+ >>> df = pd.DataFrame(d)
111
+ >>> reconstruct_data_with_by(df, by='h', cols=['a', 'b'])
112
+ h1 h2
113
+ a b a b
114
+ 0 1.0 3.0 NaN NaN
115
+ 1 3.0 4.0 NaN NaN
116
+ 2 NaN NaN 5.0 6.0
117
+ """
118
+ by_modified = unpack_single_str_list(by)
119
+ grouped = data.groupby(by_modified)
120
+
121
+ data_list = []
122
+ for key, group in grouped:
123
+ # error: List item 1 has incompatible type "Union[Hashable,
124
+ # Sequence[Hashable]]"; expected "Iterable[Hashable]"
125
+ columns = MultiIndex.from_product([[key], cols]) # type: ignore[list-item]
126
+ sub_group = group[cols]
127
+ sub_group.columns = columns
128
+ data_list.append(sub_group)
129
+
130
+ data = concat(data_list, axis=1)
131
+ return data
132
+
133
+
134
+ def reformat_hist_y_given_by(y: np.ndarray, by: IndexLabel | None) -> np.ndarray:
135
+ """Internal function to reformat y given `by` is applied or not for hist plot.
136
+
137
+ If by is None, input y is 1-d with NaN removed; and if by is not None, groupby
138
+ will take place and input y is multi-dimensional array.
139
+ """
140
+ if by is not None and len(y.shape) > 1:
141
+ return np.array([remove_na_arraylike(col) for col in y.T]).T
142
+ return remove_na_arraylike(y)
venv/lib/python3.10/site-packages/pandas/plotting/_matplotlib/hist.py ADDED
@@ -0,0 +1,581 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from typing import (
4
+ TYPE_CHECKING,
5
+ Any,
6
+ Literal,
7
+ final,
8
+ )
9
+
10
+ import numpy as np
11
+
12
+ from pandas.core.dtypes.common import (
13
+ is_integer,
14
+ is_list_like,
15
+ )
16
+ from pandas.core.dtypes.generic import (
17
+ ABCDataFrame,
18
+ ABCIndex,
19
+ )
20
+ from pandas.core.dtypes.missing import (
21
+ isna,
22
+ remove_na_arraylike,
23
+ )
24
+
25
+ from pandas.io.formats.printing import pprint_thing
26
+ from pandas.plotting._matplotlib.core import (
27
+ LinePlot,
28
+ MPLPlot,
29
+ )
30
+ from pandas.plotting._matplotlib.groupby import (
31
+ create_iter_data_given_by,
32
+ reformat_hist_y_given_by,
33
+ )
34
+ from pandas.plotting._matplotlib.misc import unpack_single_str_list
35
+ from pandas.plotting._matplotlib.tools import (
36
+ create_subplots,
37
+ flatten_axes,
38
+ maybe_adjust_figure,
39
+ set_ticks_props,
40
+ )
41
+
42
+ if TYPE_CHECKING:
43
+ from matplotlib.axes import Axes
44
+ from matplotlib.figure import Figure
45
+
46
+ from pandas._typing import PlottingOrientation
47
+
48
+ from pandas import (
49
+ DataFrame,
50
+ Series,
51
+ )
52
+
53
+
54
+ class HistPlot(LinePlot):
55
+ @property
56
+ def _kind(self) -> Literal["hist", "kde"]:
57
+ return "hist"
58
+
59
+ def __init__(
60
+ self,
61
+ data,
62
+ bins: int | np.ndarray | list[np.ndarray] = 10,
63
+ bottom: int | np.ndarray = 0,
64
+ *,
65
+ range=None,
66
+ weights=None,
67
+ **kwargs,
68
+ ) -> None:
69
+ if is_list_like(bottom):
70
+ bottom = np.array(bottom)
71
+ self.bottom = bottom
72
+
73
+ self._bin_range = range
74
+ self.weights = weights
75
+
76
+ self.xlabel = kwargs.get("xlabel")
77
+ self.ylabel = kwargs.get("ylabel")
78
+ # Do not call LinePlot.__init__ which may fill nan
79
+ MPLPlot.__init__(self, data, **kwargs) # pylint: disable=non-parent-init-called
80
+
81
+ self.bins = self._adjust_bins(bins)
82
+
83
+ def _adjust_bins(self, bins: int | np.ndarray | list[np.ndarray]):
84
+ if is_integer(bins):
85
+ if self.by is not None:
86
+ by_modified = unpack_single_str_list(self.by)
87
+ grouped = self.data.groupby(by_modified)[self.columns]
88
+ bins = [self._calculate_bins(group, bins) for key, group in grouped]
89
+ else:
90
+ bins = self._calculate_bins(self.data, bins)
91
+ return bins
92
+
93
+ def _calculate_bins(self, data: Series | DataFrame, bins) -> np.ndarray:
94
+ """Calculate bins given data"""
95
+ nd_values = data.infer_objects(copy=False)._get_numeric_data()
96
+ values = np.ravel(nd_values)
97
+ values = values[~isna(values)]
98
+
99
+ hist, bins = np.histogram(values, bins=bins, range=self._bin_range)
100
+ return bins
101
+
102
+ # error: Signature of "_plot" incompatible with supertype "LinePlot"
103
+ @classmethod
104
+ def _plot( # type: ignore[override]
105
+ cls,
106
+ ax: Axes,
107
+ y: np.ndarray,
108
+ style=None,
109
+ bottom: int | np.ndarray = 0,
110
+ column_num: int = 0,
111
+ stacking_id=None,
112
+ *,
113
+ bins,
114
+ **kwds,
115
+ ):
116
+ if column_num == 0:
117
+ cls._initialize_stacker(ax, stacking_id, len(bins) - 1)
118
+
119
+ base = np.zeros(len(bins) - 1)
120
+ bottom = bottom + cls._get_stacked_values(ax, stacking_id, base, kwds["label"])
121
+ # ignore style
122
+ n, bins, patches = ax.hist(y, bins=bins, bottom=bottom, **kwds)
123
+ cls._update_stacker(ax, stacking_id, n)
124
+ return patches
125
+
126
+ def _make_plot(self, fig: Figure) -> None:
127
+ colors = self._get_colors()
128
+ stacking_id = self._get_stacking_id()
129
+
130
+ # Re-create iterated data if `by` is assigned by users
131
+ data = (
132
+ create_iter_data_given_by(self.data, self._kind)
133
+ if self.by is not None
134
+ else self.data
135
+ )
136
+
137
+ # error: Argument "data" to "_iter_data" of "MPLPlot" has incompatible
138
+ # type "object"; expected "DataFrame | dict[Hashable, Series | DataFrame]"
139
+ for i, (label, y) in enumerate(self._iter_data(data=data)): # type: ignore[arg-type]
140
+ ax = self._get_ax(i)
141
+
142
+ kwds = self.kwds.copy()
143
+ if self.color is not None:
144
+ kwds["color"] = self.color
145
+
146
+ label = pprint_thing(label)
147
+ label = self._mark_right_label(label, index=i)
148
+ kwds["label"] = label
149
+
150
+ style, kwds = self._apply_style_colors(colors, kwds, i, label)
151
+ if style is not None:
152
+ kwds["style"] = style
153
+
154
+ self._make_plot_keywords(kwds, y)
155
+
156
+ # the bins is multi-dimension array now and each plot need only 1-d and
157
+ # when by is applied, label should be columns that are grouped
158
+ if self.by is not None:
159
+ kwds["bins"] = kwds["bins"][i]
160
+ kwds["label"] = self.columns
161
+ kwds.pop("color")
162
+
163
+ if self.weights is not None:
164
+ kwds["weights"] = type(self)._get_column_weights(self.weights, i, y)
165
+
166
+ y = reformat_hist_y_given_by(y, self.by)
167
+
168
+ artists = self._plot(ax, y, column_num=i, stacking_id=stacking_id, **kwds)
169
+
170
+ # when by is applied, show title for subplots to know which group it is
171
+ if self.by is not None:
172
+ ax.set_title(pprint_thing(label))
173
+
174
+ self._append_legend_handles_labels(artists[0], label)
175
+
176
+ def _make_plot_keywords(self, kwds: dict[str, Any], y: np.ndarray) -> None:
177
+ """merge BoxPlot/KdePlot properties to passed kwds"""
178
+ # y is required for KdePlot
179
+ kwds["bottom"] = self.bottom
180
+ kwds["bins"] = self.bins
181
+
182
+ @final
183
+ @staticmethod
184
+ def _get_column_weights(weights, i: int, y):
185
+ # We allow weights to be a multi-dimensional array, e.g. a (10, 2) array,
186
+ # and each sub-array (10,) will be called in each iteration. If users only
187
+ # provide 1D array, we assume the same weights is used for all iterations
188
+ if weights is not None:
189
+ if np.ndim(weights) != 1 and np.shape(weights)[-1] != 1:
190
+ try:
191
+ weights = weights[:, i]
192
+ except IndexError as err:
193
+ raise ValueError(
194
+ "weights must have the same shape as data, "
195
+ "or be a single column"
196
+ ) from err
197
+ weights = weights[~isna(y)]
198
+ return weights
199
+
200
+ def _post_plot_logic(self, ax: Axes, data) -> None:
201
+ if self.orientation == "horizontal":
202
+ # error: Argument 1 to "set_xlabel" of "_AxesBase" has incompatible
203
+ # type "Hashable"; expected "str"
204
+ ax.set_xlabel(
205
+ "Frequency"
206
+ if self.xlabel is None
207
+ else self.xlabel # type: ignore[arg-type]
208
+ )
209
+ ax.set_ylabel(self.ylabel) # type: ignore[arg-type]
210
+ else:
211
+ ax.set_xlabel(self.xlabel) # type: ignore[arg-type]
212
+ ax.set_ylabel(
213
+ "Frequency"
214
+ if self.ylabel is None
215
+ else self.ylabel # type: ignore[arg-type]
216
+ )
217
+
218
+ @property
219
+ def orientation(self) -> PlottingOrientation:
220
+ if self.kwds.get("orientation", None) == "horizontal":
221
+ return "horizontal"
222
+ else:
223
+ return "vertical"
224
+
225
+
226
+ class KdePlot(HistPlot):
227
+ @property
228
+ def _kind(self) -> Literal["kde"]:
229
+ return "kde"
230
+
231
+ @property
232
+ def orientation(self) -> Literal["vertical"]:
233
+ return "vertical"
234
+
235
+ def __init__(
236
+ self, data, bw_method=None, ind=None, *, weights=None, **kwargs
237
+ ) -> None:
238
+ # Do not call LinePlot.__init__ which may fill nan
239
+ MPLPlot.__init__(self, data, **kwargs) # pylint: disable=non-parent-init-called
240
+ self.bw_method = bw_method
241
+ self.ind = ind
242
+ self.weights = weights
243
+
244
+ @staticmethod
245
+ def _get_ind(y: np.ndarray, ind):
246
+ if ind is None:
247
+ # np.nanmax() and np.nanmin() ignores the missing values
248
+ sample_range = np.nanmax(y) - np.nanmin(y)
249
+ ind = np.linspace(
250
+ np.nanmin(y) - 0.5 * sample_range,
251
+ np.nanmax(y) + 0.5 * sample_range,
252
+ 1000,
253
+ )
254
+ elif is_integer(ind):
255
+ sample_range = np.nanmax(y) - np.nanmin(y)
256
+ ind = np.linspace(
257
+ np.nanmin(y) - 0.5 * sample_range,
258
+ np.nanmax(y) + 0.5 * sample_range,
259
+ ind,
260
+ )
261
+ return ind
262
+
263
+ @classmethod
264
+ # error: Signature of "_plot" incompatible with supertype "MPLPlot"
265
+ def _plot( # type: ignore[override]
266
+ cls,
267
+ ax: Axes,
268
+ y: np.ndarray,
269
+ style=None,
270
+ bw_method=None,
271
+ ind=None,
272
+ column_num=None,
273
+ stacking_id: int | None = None,
274
+ **kwds,
275
+ ):
276
+ from scipy.stats import gaussian_kde
277
+
278
+ y = remove_na_arraylike(y)
279
+ gkde = gaussian_kde(y, bw_method=bw_method)
280
+
281
+ y = gkde.evaluate(ind)
282
+ lines = MPLPlot._plot(ax, ind, y, style=style, **kwds)
283
+ return lines
284
+
285
+ def _make_plot_keywords(self, kwds: dict[str, Any], y: np.ndarray) -> None:
286
+ kwds["bw_method"] = self.bw_method
287
+ kwds["ind"] = type(self)._get_ind(y, ind=self.ind)
288
+
289
+ def _post_plot_logic(self, ax: Axes, data) -> None:
290
+ ax.set_ylabel("Density")
291
+
292
+
293
+ def _grouped_plot(
294
+ plotf,
295
+ data: Series | DataFrame,
296
+ column=None,
297
+ by=None,
298
+ numeric_only: bool = True,
299
+ figsize: tuple[float, float] | None = None,
300
+ sharex: bool = True,
301
+ sharey: bool = True,
302
+ layout=None,
303
+ rot: float = 0,
304
+ ax=None,
305
+ **kwargs,
306
+ ):
307
+ # error: Non-overlapping equality check (left operand type: "Optional[Tuple[float,
308
+ # float]]", right operand type: "Literal['default']")
309
+ if figsize == "default": # type: ignore[comparison-overlap]
310
+ # allowed to specify mpl default with 'default'
311
+ raise ValueError(
312
+ "figsize='default' is no longer supported. "
313
+ "Specify figure size by tuple instead"
314
+ )
315
+
316
+ grouped = data.groupby(by)
317
+ if column is not None:
318
+ grouped = grouped[column]
319
+
320
+ naxes = len(grouped)
321
+ fig, axes = create_subplots(
322
+ naxes=naxes, figsize=figsize, sharex=sharex, sharey=sharey, ax=ax, layout=layout
323
+ )
324
+
325
+ _axes = flatten_axes(axes)
326
+
327
+ for i, (key, group) in enumerate(grouped):
328
+ ax = _axes[i]
329
+ if numeric_only and isinstance(group, ABCDataFrame):
330
+ group = group._get_numeric_data()
331
+ plotf(group, ax, **kwargs)
332
+ ax.set_title(pprint_thing(key))
333
+
334
+ return fig, axes
335
+
336
+
337
+ def _grouped_hist(
338
+ data: Series | DataFrame,
339
+ column=None,
340
+ by=None,
341
+ ax=None,
342
+ bins: int = 50,
343
+ figsize: tuple[float, float] | None = None,
344
+ layout=None,
345
+ sharex: bool = False,
346
+ sharey: bool = False,
347
+ rot: float = 90,
348
+ grid: bool = True,
349
+ xlabelsize: int | None = None,
350
+ xrot=None,
351
+ ylabelsize: int | None = None,
352
+ yrot=None,
353
+ legend: bool = False,
354
+ **kwargs,
355
+ ):
356
+ """
357
+ Grouped histogram
358
+
359
+ Parameters
360
+ ----------
361
+ data : Series/DataFrame
362
+ column : object, optional
363
+ by : object, optional
364
+ ax : axes, optional
365
+ bins : int, default 50
366
+ figsize : tuple, optional
367
+ layout : optional
368
+ sharex : bool, default False
369
+ sharey : bool, default False
370
+ rot : float, default 90
371
+ grid : bool, default True
372
+ legend: : bool, default False
373
+ kwargs : dict, keyword arguments passed to matplotlib.Axes.hist
374
+
375
+ Returns
376
+ -------
377
+ collection of Matplotlib Axes
378
+ """
379
+ if legend:
380
+ assert "label" not in kwargs
381
+ if data.ndim == 1:
382
+ kwargs["label"] = data.name
383
+ elif column is None:
384
+ kwargs["label"] = data.columns
385
+ else:
386
+ kwargs["label"] = column
387
+
388
+ def plot_group(group, ax) -> None:
389
+ ax.hist(group.dropna().values, bins=bins, **kwargs)
390
+ if legend:
391
+ ax.legend()
392
+
393
+ if xrot is None:
394
+ xrot = rot
395
+
396
+ fig, axes = _grouped_plot(
397
+ plot_group,
398
+ data,
399
+ column=column,
400
+ by=by,
401
+ sharex=sharex,
402
+ sharey=sharey,
403
+ ax=ax,
404
+ figsize=figsize,
405
+ layout=layout,
406
+ rot=rot,
407
+ )
408
+
409
+ set_ticks_props(
410
+ axes, xlabelsize=xlabelsize, xrot=xrot, ylabelsize=ylabelsize, yrot=yrot
411
+ )
412
+
413
+ maybe_adjust_figure(
414
+ fig, bottom=0.15, top=0.9, left=0.1, right=0.9, hspace=0.5, wspace=0.3
415
+ )
416
+ return axes
417
+
418
+
419
+ def hist_series(
420
+ self: Series,
421
+ by=None,
422
+ ax=None,
423
+ grid: bool = True,
424
+ xlabelsize: int | None = None,
425
+ xrot=None,
426
+ ylabelsize: int | None = None,
427
+ yrot=None,
428
+ figsize: tuple[float, float] | None = None,
429
+ bins: int = 10,
430
+ legend: bool = False,
431
+ **kwds,
432
+ ):
433
+ import matplotlib.pyplot as plt
434
+
435
+ if legend and "label" in kwds:
436
+ raise ValueError("Cannot use both legend and label")
437
+
438
+ if by is None:
439
+ if kwds.get("layout", None) is not None:
440
+ raise ValueError("The 'layout' keyword is not supported when 'by' is None")
441
+ # hack until the plotting interface is a bit more unified
442
+ fig = kwds.pop(
443
+ "figure", plt.gcf() if plt.get_fignums() else plt.figure(figsize=figsize)
444
+ )
445
+ if figsize is not None and tuple(figsize) != tuple(fig.get_size_inches()):
446
+ fig.set_size_inches(*figsize, forward=True)
447
+ if ax is None:
448
+ ax = fig.gca()
449
+ elif ax.get_figure() != fig:
450
+ raise AssertionError("passed axis not bound to passed figure")
451
+ values = self.dropna().values
452
+ if legend:
453
+ kwds["label"] = self.name
454
+ ax.hist(values, bins=bins, **kwds)
455
+ if legend:
456
+ ax.legend()
457
+ ax.grid(grid)
458
+ axes = np.array([ax])
459
+
460
+ # error: Argument 1 to "set_ticks_props" has incompatible type "ndarray[Any,
461
+ # dtype[Any]]"; expected "Axes | Sequence[Axes]"
462
+ set_ticks_props(
463
+ axes, # type: ignore[arg-type]
464
+ xlabelsize=xlabelsize,
465
+ xrot=xrot,
466
+ ylabelsize=ylabelsize,
467
+ yrot=yrot,
468
+ )
469
+
470
+ else:
471
+ if "figure" in kwds:
472
+ raise ValueError(
473
+ "Cannot pass 'figure' when using the "
474
+ "'by' argument, since a new 'Figure' instance will be created"
475
+ )
476
+ axes = _grouped_hist(
477
+ self,
478
+ by=by,
479
+ ax=ax,
480
+ grid=grid,
481
+ figsize=figsize,
482
+ bins=bins,
483
+ xlabelsize=xlabelsize,
484
+ xrot=xrot,
485
+ ylabelsize=ylabelsize,
486
+ yrot=yrot,
487
+ legend=legend,
488
+ **kwds,
489
+ )
490
+
491
+ if hasattr(axes, "ndim"):
492
+ if axes.ndim == 1 and len(axes) == 1:
493
+ return axes[0]
494
+ return axes
495
+
496
+
497
+ def hist_frame(
498
+ data: DataFrame,
499
+ column=None,
500
+ by=None,
501
+ grid: bool = True,
502
+ xlabelsize: int | None = None,
503
+ xrot=None,
504
+ ylabelsize: int | None = None,
505
+ yrot=None,
506
+ ax=None,
507
+ sharex: bool = False,
508
+ sharey: bool = False,
509
+ figsize: tuple[float, float] | None = None,
510
+ layout=None,
511
+ bins: int = 10,
512
+ legend: bool = False,
513
+ **kwds,
514
+ ):
515
+ if legend and "label" in kwds:
516
+ raise ValueError("Cannot use both legend and label")
517
+ if by is not None:
518
+ axes = _grouped_hist(
519
+ data,
520
+ column=column,
521
+ by=by,
522
+ ax=ax,
523
+ grid=grid,
524
+ figsize=figsize,
525
+ sharex=sharex,
526
+ sharey=sharey,
527
+ layout=layout,
528
+ bins=bins,
529
+ xlabelsize=xlabelsize,
530
+ xrot=xrot,
531
+ ylabelsize=ylabelsize,
532
+ yrot=yrot,
533
+ legend=legend,
534
+ **kwds,
535
+ )
536
+ return axes
537
+
538
+ if column is not None:
539
+ if not isinstance(column, (list, np.ndarray, ABCIndex)):
540
+ column = [column]
541
+ data = data[column]
542
+ # GH32590
543
+ data = data.select_dtypes(
544
+ include=(np.number, "datetime64", "datetimetz"), exclude="timedelta"
545
+ )
546
+ naxes = len(data.columns)
547
+
548
+ if naxes == 0:
549
+ raise ValueError(
550
+ "hist method requires numerical or datetime columns, nothing to plot."
551
+ )
552
+
553
+ fig, axes = create_subplots(
554
+ naxes=naxes,
555
+ ax=ax,
556
+ squeeze=False,
557
+ sharex=sharex,
558
+ sharey=sharey,
559
+ figsize=figsize,
560
+ layout=layout,
561
+ )
562
+ _axes = flatten_axes(axes)
563
+
564
+ can_set_label = "label" not in kwds
565
+
566
+ for i, col in enumerate(data.columns):
567
+ ax = _axes[i]
568
+ if legend and can_set_label:
569
+ kwds["label"] = col
570
+ ax.hist(data[col].dropna().values, bins=bins, **kwds)
571
+ ax.set_title(col)
572
+ ax.grid(grid)
573
+ if legend:
574
+ ax.legend()
575
+
576
+ set_ticks_props(
577
+ axes, xlabelsize=xlabelsize, xrot=xrot, ylabelsize=ylabelsize, yrot=yrot
578
+ )
579
+ maybe_adjust_figure(fig, wspace=0.3, hspace=0.3)
580
+
581
+ return axes
venv/lib/python3.10/site-packages/pandas/plotting/_matplotlib/misc.py ADDED
@@ -0,0 +1,481 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import random
4
+ from typing import TYPE_CHECKING
5
+
6
+ from matplotlib import patches
7
+ import matplotlib.lines as mlines
8
+ import numpy as np
9
+
10
+ from pandas.core.dtypes.missing import notna
11
+
12
+ from pandas.io.formats.printing import pprint_thing
13
+ from pandas.plotting._matplotlib.style import get_standard_colors
14
+ from pandas.plotting._matplotlib.tools import (
15
+ create_subplots,
16
+ do_adjust_figure,
17
+ maybe_adjust_figure,
18
+ set_ticks_props,
19
+ )
20
+
21
+ if TYPE_CHECKING:
22
+ from collections.abc import Hashable
23
+
24
+ from matplotlib.axes import Axes
25
+ from matplotlib.figure import Figure
26
+
27
+ from pandas import (
28
+ DataFrame,
29
+ Index,
30
+ Series,
31
+ )
32
+
33
+
34
+ def scatter_matrix(
35
+ frame: DataFrame,
36
+ alpha: float = 0.5,
37
+ figsize: tuple[float, float] | None = None,
38
+ ax=None,
39
+ grid: bool = False,
40
+ diagonal: str = "hist",
41
+ marker: str = ".",
42
+ density_kwds=None,
43
+ hist_kwds=None,
44
+ range_padding: float = 0.05,
45
+ **kwds,
46
+ ):
47
+ df = frame._get_numeric_data()
48
+ n = df.columns.size
49
+ naxes = n * n
50
+ fig, axes = create_subplots(naxes=naxes, figsize=figsize, ax=ax, squeeze=False)
51
+
52
+ # no gaps between subplots
53
+ maybe_adjust_figure(fig, wspace=0, hspace=0)
54
+
55
+ mask = notna(df)
56
+
57
+ marker = _get_marker_compat(marker)
58
+
59
+ hist_kwds = hist_kwds or {}
60
+ density_kwds = density_kwds or {}
61
+
62
+ # GH 14855
63
+ kwds.setdefault("edgecolors", "none")
64
+
65
+ boundaries_list = []
66
+ for a in df.columns:
67
+ values = df[a].values[mask[a].values]
68
+ rmin_, rmax_ = np.min(values), np.max(values)
69
+ rdelta_ext = (rmax_ - rmin_) * range_padding / 2
70
+ boundaries_list.append((rmin_ - rdelta_ext, rmax_ + rdelta_ext))
71
+
72
+ for i, a in enumerate(df.columns):
73
+ for j, b in enumerate(df.columns):
74
+ ax = axes[i, j]
75
+
76
+ if i == j:
77
+ values = df[a].values[mask[a].values]
78
+
79
+ # Deal with the diagonal by drawing a histogram there.
80
+ if diagonal == "hist":
81
+ ax.hist(values, **hist_kwds)
82
+
83
+ elif diagonal in ("kde", "density"):
84
+ from scipy.stats import gaussian_kde
85
+
86
+ y = values
87
+ gkde = gaussian_kde(y)
88
+ ind = np.linspace(y.min(), y.max(), 1000)
89
+ ax.plot(ind, gkde.evaluate(ind), **density_kwds)
90
+
91
+ ax.set_xlim(boundaries_list[i])
92
+
93
+ else:
94
+ common = (mask[a] & mask[b]).values
95
+
96
+ ax.scatter(
97
+ df[b][common], df[a][common], marker=marker, alpha=alpha, **kwds
98
+ )
99
+
100
+ ax.set_xlim(boundaries_list[j])
101
+ ax.set_ylim(boundaries_list[i])
102
+
103
+ ax.set_xlabel(b)
104
+ ax.set_ylabel(a)
105
+
106
+ if j != 0:
107
+ ax.yaxis.set_visible(False)
108
+ if i != n - 1:
109
+ ax.xaxis.set_visible(False)
110
+
111
+ if len(df.columns) > 1:
112
+ lim1 = boundaries_list[0]
113
+ locs = axes[0][1].yaxis.get_majorticklocs()
114
+ locs = locs[(lim1[0] <= locs) & (locs <= lim1[1])]
115
+ adj = (locs - lim1[0]) / (lim1[1] - lim1[0])
116
+
117
+ lim0 = axes[0][0].get_ylim()
118
+ adj = adj * (lim0[1] - lim0[0]) + lim0[0]
119
+ axes[0][0].yaxis.set_ticks(adj)
120
+
121
+ if np.all(locs == locs.astype(int)):
122
+ # if all ticks are int
123
+ locs = locs.astype(int)
124
+ axes[0][0].yaxis.set_ticklabels(locs)
125
+
126
+ set_ticks_props(axes, xlabelsize=8, xrot=90, ylabelsize=8, yrot=0)
127
+
128
+ return axes
129
+
130
+
131
+ def _get_marker_compat(marker):
132
+ if marker not in mlines.lineMarkers:
133
+ return "o"
134
+ return marker
135
+
136
+
137
+ def radviz(
138
+ frame: DataFrame,
139
+ class_column,
140
+ ax: Axes | None = None,
141
+ color=None,
142
+ colormap=None,
143
+ **kwds,
144
+ ) -> Axes:
145
+ import matplotlib.pyplot as plt
146
+
147
+ def normalize(series):
148
+ a = min(series)
149
+ b = max(series)
150
+ return (series - a) / (b - a)
151
+
152
+ n = len(frame)
153
+ classes = frame[class_column].drop_duplicates()
154
+ class_col = frame[class_column]
155
+ df = frame.drop(class_column, axis=1).apply(normalize)
156
+
157
+ if ax is None:
158
+ ax = plt.gca()
159
+ ax.set_xlim(-1, 1)
160
+ ax.set_ylim(-1, 1)
161
+
162
+ to_plot: dict[Hashable, list[list]] = {}
163
+ colors = get_standard_colors(
164
+ num_colors=len(classes), colormap=colormap, color_type="random", color=color
165
+ )
166
+
167
+ for kls in classes:
168
+ to_plot[kls] = [[], []]
169
+
170
+ m = len(frame.columns) - 1
171
+ s = np.array(
172
+ [(np.cos(t), np.sin(t)) for t in [2 * np.pi * (i / m) for i in range(m)]]
173
+ )
174
+
175
+ for i in range(n):
176
+ row = df.iloc[i].values
177
+ row_ = np.repeat(np.expand_dims(row, axis=1), 2, axis=1)
178
+ y = (s * row_).sum(axis=0) / row.sum()
179
+ kls = class_col.iat[i]
180
+ to_plot[kls][0].append(y[0])
181
+ to_plot[kls][1].append(y[1])
182
+
183
+ for i, kls in enumerate(classes):
184
+ ax.scatter(
185
+ to_plot[kls][0],
186
+ to_plot[kls][1],
187
+ color=colors[i],
188
+ label=pprint_thing(kls),
189
+ **kwds,
190
+ )
191
+ ax.legend()
192
+
193
+ ax.add_patch(patches.Circle((0.0, 0.0), radius=1.0, facecolor="none"))
194
+
195
+ for xy, name in zip(s, df.columns):
196
+ ax.add_patch(patches.Circle(xy, radius=0.025, facecolor="gray"))
197
+
198
+ if xy[0] < 0.0 and xy[1] < 0.0:
199
+ ax.text(
200
+ xy[0] - 0.025, xy[1] - 0.025, name, ha="right", va="top", size="small"
201
+ )
202
+ elif xy[0] < 0.0 <= xy[1]:
203
+ ax.text(
204
+ xy[0] - 0.025,
205
+ xy[1] + 0.025,
206
+ name,
207
+ ha="right",
208
+ va="bottom",
209
+ size="small",
210
+ )
211
+ elif xy[1] < 0.0 <= xy[0]:
212
+ ax.text(
213
+ xy[0] + 0.025, xy[1] - 0.025, name, ha="left", va="top", size="small"
214
+ )
215
+ elif xy[0] >= 0.0 and xy[1] >= 0.0:
216
+ ax.text(
217
+ xy[0] + 0.025, xy[1] + 0.025, name, ha="left", va="bottom", size="small"
218
+ )
219
+
220
+ ax.axis("equal")
221
+ return ax
222
+
223
+
224
+ def andrews_curves(
225
+ frame: DataFrame,
226
+ class_column,
227
+ ax: Axes | None = None,
228
+ samples: int = 200,
229
+ color=None,
230
+ colormap=None,
231
+ **kwds,
232
+ ) -> Axes:
233
+ import matplotlib.pyplot as plt
234
+
235
+ def function(amplitudes):
236
+ def f(t):
237
+ x1 = amplitudes[0]
238
+ result = x1 / np.sqrt(2.0)
239
+
240
+ # Take the rest of the coefficients and resize them
241
+ # appropriately. Take a copy of amplitudes as otherwise numpy
242
+ # deletes the element from amplitudes itself.
243
+ coeffs = np.delete(np.copy(amplitudes), 0)
244
+ coeffs = np.resize(coeffs, (int((coeffs.size + 1) / 2), 2))
245
+
246
+ # Generate the harmonics and arguments for the sin and cos
247
+ # functions.
248
+ harmonics = np.arange(0, coeffs.shape[0]) + 1
249
+ trig_args = np.outer(harmonics, t)
250
+
251
+ result += np.sum(
252
+ coeffs[:, 0, np.newaxis] * np.sin(trig_args)
253
+ + coeffs[:, 1, np.newaxis] * np.cos(trig_args),
254
+ axis=0,
255
+ )
256
+ return result
257
+
258
+ return f
259
+
260
+ n = len(frame)
261
+ class_col = frame[class_column]
262
+ classes = frame[class_column].drop_duplicates()
263
+ df = frame.drop(class_column, axis=1)
264
+ t = np.linspace(-np.pi, np.pi, samples)
265
+ used_legends: set[str] = set()
266
+
267
+ color_values = get_standard_colors(
268
+ num_colors=len(classes), colormap=colormap, color_type="random", color=color
269
+ )
270
+ colors = dict(zip(classes, color_values))
271
+ if ax is None:
272
+ ax = plt.gca()
273
+ ax.set_xlim(-np.pi, np.pi)
274
+ for i in range(n):
275
+ row = df.iloc[i].values
276
+ f = function(row)
277
+ y = f(t)
278
+ kls = class_col.iat[i]
279
+ label = pprint_thing(kls)
280
+ if label not in used_legends:
281
+ used_legends.add(label)
282
+ ax.plot(t, y, color=colors[kls], label=label, **kwds)
283
+ else:
284
+ ax.plot(t, y, color=colors[kls], **kwds)
285
+
286
+ ax.legend(loc="upper right")
287
+ ax.grid()
288
+ return ax
289
+
290
+
291
+ def bootstrap_plot(
292
+ series: Series,
293
+ fig: Figure | None = None,
294
+ size: int = 50,
295
+ samples: int = 500,
296
+ **kwds,
297
+ ) -> Figure:
298
+ import matplotlib.pyplot as plt
299
+
300
+ # TODO: is the failure mentioned below still relevant?
301
+ # random.sample(ndarray, int) fails on python 3.3, sigh
302
+ data = list(series.values)
303
+ samplings = [random.sample(data, size) for _ in range(samples)]
304
+
305
+ means = np.array([np.mean(sampling) for sampling in samplings])
306
+ medians = np.array([np.median(sampling) for sampling in samplings])
307
+ midranges = np.array(
308
+ [(min(sampling) + max(sampling)) * 0.5 for sampling in samplings]
309
+ )
310
+ if fig is None:
311
+ fig = plt.figure()
312
+ x = list(range(samples))
313
+ axes = []
314
+ ax1 = fig.add_subplot(2, 3, 1)
315
+ ax1.set_xlabel("Sample")
316
+ axes.append(ax1)
317
+ ax1.plot(x, means, **kwds)
318
+ ax2 = fig.add_subplot(2, 3, 2)
319
+ ax2.set_xlabel("Sample")
320
+ axes.append(ax2)
321
+ ax2.plot(x, medians, **kwds)
322
+ ax3 = fig.add_subplot(2, 3, 3)
323
+ ax3.set_xlabel("Sample")
324
+ axes.append(ax3)
325
+ ax3.plot(x, midranges, **kwds)
326
+ ax4 = fig.add_subplot(2, 3, 4)
327
+ ax4.set_xlabel("Mean")
328
+ axes.append(ax4)
329
+ ax4.hist(means, **kwds)
330
+ ax5 = fig.add_subplot(2, 3, 5)
331
+ ax5.set_xlabel("Median")
332
+ axes.append(ax5)
333
+ ax5.hist(medians, **kwds)
334
+ ax6 = fig.add_subplot(2, 3, 6)
335
+ ax6.set_xlabel("Midrange")
336
+ axes.append(ax6)
337
+ ax6.hist(midranges, **kwds)
338
+ for axis in axes:
339
+ plt.setp(axis.get_xticklabels(), fontsize=8)
340
+ plt.setp(axis.get_yticklabels(), fontsize=8)
341
+ if do_adjust_figure(fig):
342
+ plt.tight_layout()
343
+ return fig
344
+
345
+
346
+ def parallel_coordinates(
347
+ frame: DataFrame,
348
+ class_column,
349
+ cols=None,
350
+ ax: Axes | None = None,
351
+ color=None,
352
+ use_columns: bool = False,
353
+ xticks=None,
354
+ colormap=None,
355
+ axvlines: bool = True,
356
+ axvlines_kwds=None,
357
+ sort_labels: bool = False,
358
+ **kwds,
359
+ ) -> Axes:
360
+ import matplotlib.pyplot as plt
361
+
362
+ if axvlines_kwds is None:
363
+ axvlines_kwds = {"linewidth": 1, "color": "black"}
364
+
365
+ n = len(frame)
366
+ classes = frame[class_column].drop_duplicates()
367
+ class_col = frame[class_column]
368
+
369
+ if cols is None:
370
+ df = frame.drop(class_column, axis=1)
371
+ else:
372
+ df = frame[cols]
373
+
374
+ used_legends: set[str] = set()
375
+
376
+ ncols = len(df.columns)
377
+
378
+ # determine values to use for xticks
379
+ x: list[int] | Index
380
+ if use_columns is True:
381
+ if not np.all(np.isreal(list(df.columns))):
382
+ raise ValueError("Columns must be numeric to be used as xticks")
383
+ x = df.columns
384
+ elif xticks is not None:
385
+ if not np.all(np.isreal(xticks)):
386
+ raise ValueError("xticks specified must be numeric")
387
+ if len(xticks) != ncols:
388
+ raise ValueError("Length of xticks must match number of columns")
389
+ x = xticks
390
+ else:
391
+ x = list(range(ncols))
392
+
393
+ if ax is None:
394
+ ax = plt.gca()
395
+
396
+ color_values = get_standard_colors(
397
+ num_colors=len(classes), colormap=colormap, color_type="random", color=color
398
+ )
399
+
400
+ if sort_labels:
401
+ classes = sorted(classes)
402
+ color_values = sorted(color_values)
403
+ colors = dict(zip(classes, color_values))
404
+
405
+ for i in range(n):
406
+ y = df.iloc[i].values
407
+ kls = class_col.iat[i]
408
+ label = pprint_thing(kls)
409
+ if label not in used_legends:
410
+ used_legends.add(label)
411
+ ax.plot(x, y, color=colors[kls], label=label, **kwds)
412
+ else:
413
+ ax.plot(x, y, color=colors[kls], **kwds)
414
+
415
+ if axvlines:
416
+ for i in x:
417
+ ax.axvline(i, **axvlines_kwds)
418
+
419
+ ax.set_xticks(x)
420
+ ax.set_xticklabels(df.columns)
421
+ ax.set_xlim(x[0], x[-1])
422
+ ax.legend(loc="upper right")
423
+ ax.grid()
424
+ return ax
425
+
426
+
427
+ def lag_plot(series: Series, lag: int = 1, ax: Axes | None = None, **kwds) -> Axes:
428
+ # workaround because `c='b'` is hardcoded in matplotlib's scatter method
429
+ import matplotlib.pyplot as plt
430
+
431
+ kwds.setdefault("c", plt.rcParams["patch.facecolor"])
432
+
433
+ data = series.values
434
+ y1 = data[:-lag]
435
+ y2 = data[lag:]
436
+ if ax is None:
437
+ ax = plt.gca()
438
+ ax.set_xlabel("y(t)")
439
+ ax.set_ylabel(f"y(t + {lag})")
440
+ ax.scatter(y1, y2, **kwds)
441
+ return ax
442
+
443
+
444
+ def autocorrelation_plot(series: Series, ax: Axes | None = None, **kwds) -> Axes:
445
+ import matplotlib.pyplot as plt
446
+
447
+ n = len(series)
448
+ data = np.asarray(series)
449
+ if ax is None:
450
+ ax = plt.gca()
451
+ ax.set_xlim(1, n)
452
+ ax.set_ylim(-1.0, 1.0)
453
+ mean = np.mean(data)
454
+ c0 = np.sum((data - mean) ** 2) / n
455
+
456
+ def r(h):
457
+ return ((data[: n - h] - mean) * (data[h:] - mean)).sum() / n / c0
458
+
459
+ x = np.arange(n) + 1
460
+ y = [r(loc) for loc in x]
461
+ z95 = 1.959963984540054
462
+ z99 = 2.5758293035489004
463
+ ax.axhline(y=z99 / np.sqrt(n), linestyle="--", color="grey")
464
+ ax.axhline(y=z95 / np.sqrt(n), color="grey")
465
+ ax.axhline(y=0.0, color="black")
466
+ ax.axhline(y=-z95 / np.sqrt(n), color="grey")
467
+ ax.axhline(y=-z99 / np.sqrt(n), linestyle="--", color="grey")
468
+ ax.set_xlabel("Lag")
469
+ ax.set_ylabel("Autocorrelation")
470
+ ax.plot(x, y, **kwds)
471
+ if "label" in kwds:
472
+ ax.legend()
473
+ ax.grid()
474
+ return ax
475
+
476
+
477
+ def unpack_single_str_list(keys):
478
+ # GH 42795
479
+ if isinstance(keys, list) and len(keys) == 1:
480
+ keys = keys[0]
481
+ return keys
venv/lib/python3.10/site-packages/pandas/plotting/_matplotlib/style.py ADDED
@@ -0,0 +1,278 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from collections.abc import (
4
+ Collection,
5
+ Iterator,
6
+ )
7
+ import itertools
8
+ from typing import (
9
+ TYPE_CHECKING,
10
+ cast,
11
+ )
12
+ import warnings
13
+
14
+ import matplotlib as mpl
15
+ import matplotlib.colors
16
+ import numpy as np
17
+
18
+ from pandas._typing import MatplotlibColor as Color
19
+ from pandas.util._exceptions import find_stack_level
20
+
21
+ from pandas.core.dtypes.common import is_list_like
22
+
23
+ import pandas.core.common as com
24
+
25
+ if TYPE_CHECKING:
26
+ from matplotlib.colors import Colormap
27
+
28
+
29
+ def get_standard_colors(
30
+ num_colors: int,
31
+ colormap: Colormap | None = None,
32
+ color_type: str = "default",
33
+ color: dict[str, Color] | Color | Collection[Color] | None = None,
34
+ ):
35
+ """
36
+ Get standard colors based on `colormap`, `color_type` or `color` inputs.
37
+
38
+ Parameters
39
+ ----------
40
+ num_colors : int
41
+ Minimum number of colors to be returned.
42
+ Ignored if `color` is a dictionary.
43
+ colormap : :py:class:`matplotlib.colors.Colormap`, optional
44
+ Matplotlib colormap.
45
+ When provided, the resulting colors will be derived from the colormap.
46
+ color_type : {"default", "random"}, optional
47
+ Type of colors to derive. Used if provided `color` and `colormap` are None.
48
+ Ignored if either `color` or `colormap` are not None.
49
+ color : dict or str or sequence, optional
50
+ Color(s) to be used for deriving sequence of colors.
51
+ Can be either be a dictionary, or a single color (single color string,
52
+ or sequence of floats representing a single color),
53
+ or a sequence of colors.
54
+
55
+ Returns
56
+ -------
57
+ dict or list
58
+ Standard colors. Can either be a mapping if `color` was a dictionary,
59
+ or a list of colors with a length of `num_colors` or more.
60
+
61
+ Warns
62
+ -----
63
+ UserWarning
64
+ If both `colormap` and `color` are provided.
65
+ Parameter `color` will override.
66
+ """
67
+ if isinstance(color, dict):
68
+ return color
69
+
70
+ colors = _derive_colors(
71
+ color=color,
72
+ colormap=colormap,
73
+ color_type=color_type,
74
+ num_colors=num_colors,
75
+ )
76
+
77
+ return list(_cycle_colors(colors, num_colors=num_colors))
78
+
79
+
80
+ def _derive_colors(
81
+ *,
82
+ color: Color | Collection[Color] | None,
83
+ colormap: str | Colormap | None,
84
+ color_type: str,
85
+ num_colors: int,
86
+ ) -> list[Color]:
87
+ """
88
+ Derive colors from either `colormap`, `color_type` or `color` inputs.
89
+
90
+ Get a list of colors either from `colormap`, or from `color`,
91
+ or from `color_type` (if both `colormap` and `color` are None).
92
+
93
+ Parameters
94
+ ----------
95
+ color : str or sequence, optional
96
+ Color(s) to be used for deriving sequence of colors.
97
+ Can be either be a single color (single color string, or sequence of floats
98
+ representing a single color), or a sequence of colors.
99
+ colormap : :py:class:`matplotlib.colors.Colormap`, optional
100
+ Matplotlib colormap.
101
+ When provided, the resulting colors will be derived from the colormap.
102
+ color_type : {"default", "random"}, optional
103
+ Type of colors to derive. Used if provided `color` and `colormap` are None.
104
+ Ignored if either `color` or `colormap`` are not None.
105
+ num_colors : int
106
+ Number of colors to be extracted.
107
+
108
+ Returns
109
+ -------
110
+ list
111
+ List of colors extracted.
112
+
113
+ Warns
114
+ -----
115
+ UserWarning
116
+ If both `colormap` and `color` are provided.
117
+ Parameter `color` will override.
118
+ """
119
+ if color is None and colormap is not None:
120
+ return _get_colors_from_colormap(colormap, num_colors=num_colors)
121
+ elif color is not None:
122
+ if colormap is not None:
123
+ warnings.warn(
124
+ "'color' and 'colormap' cannot be used simultaneously. Using 'color'",
125
+ stacklevel=find_stack_level(),
126
+ )
127
+ return _get_colors_from_color(color)
128
+ else:
129
+ return _get_colors_from_color_type(color_type, num_colors=num_colors)
130
+
131
+
132
+ def _cycle_colors(colors: list[Color], num_colors: int) -> Iterator[Color]:
133
+ """Cycle colors until achieving max of `num_colors` or length of `colors`.
134
+
135
+ Extra colors will be ignored by matplotlib if there are more colors
136
+ than needed and nothing needs to be done here.
137
+ """
138
+ max_colors = max(num_colors, len(colors))
139
+ yield from itertools.islice(itertools.cycle(colors), max_colors)
140
+
141
+
142
+ def _get_colors_from_colormap(
143
+ colormap: str | Colormap,
144
+ num_colors: int,
145
+ ) -> list[Color]:
146
+ """Get colors from colormap."""
147
+ cmap = _get_cmap_instance(colormap)
148
+ return [cmap(num) for num in np.linspace(0, 1, num=num_colors)]
149
+
150
+
151
+ def _get_cmap_instance(colormap: str | Colormap) -> Colormap:
152
+ """Get instance of matplotlib colormap."""
153
+ if isinstance(colormap, str):
154
+ cmap = colormap
155
+ colormap = mpl.colormaps[colormap]
156
+ if colormap is None:
157
+ raise ValueError(f"Colormap {cmap} is not recognized")
158
+ return colormap
159
+
160
+
161
+ def _get_colors_from_color(
162
+ color: Color | Collection[Color],
163
+ ) -> list[Color]:
164
+ """Get colors from user input color."""
165
+ if len(color) == 0:
166
+ raise ValueError(f"Invalid color argument: {color}")
167
+
168
+ if _is_single_color(color):
169
+ color = cast(Color, color)
170
+ return [color]
171
+
172
+ color = cast(Collection[Color], color)
173
+ return list(_gen_list_of_colors_from_iterable(color))
174
+
175
+
176
+ def _is_single_color(color: Color | Collection[Color]) -> bool:
177
+ """Check if `color` is a single color, not a sequence of colors.
178
+
179
+ Single color is of these kinds:
180
+ - Named color "red", "C0", "firebrick"
181
+ - Alias "g"
182
+ - Sequence of floats, such as (0.1, 0.2, 0.3) or (0.1, 0.2, 0.3, 0.4).
183
+
184
+ See Also
185
+ --------
186
+ _is_single_string_color
187
+ """
188
+ if isinstance(color, str) and _is_single_string_color(color):
189
+ # GH #36972
190
+ return True
191
+
192
+ if _is_floats_color(color):
193
+ return True
194
+
195
+ return False
196
+
197
+
198
+ def _gen_list_of_colors_from_iterable(color: Collection[Color]) -> Iterator[Color]:
199
+ """
200
+ Yield colors from string of several letters or from collection of colors.
201
+ """
202
+ for x in color:
203
+ if _is_single_color(x):
204
+ yield x
205
+ else:
206
+ raise ValueError(f"Invalid color {x}")
207
+
208
+
209
+ def _is_floats_color(color: Color | Collection[Color]) -> bool:
210
+ """Check if color comprises a sequence of floats representing color."""
211
+ return bool(
212
+ is_list_like(color)
213
+ and (len(color) == 3 or len(color) == 4)
214
+ and all(isinstance(x, (int, float)) for x in color)
215
+ )
216
+
217
+
218
+ def _get_colors_from_color_type(color_type: str, num_colors: int) -> list[Color]:
219
+ """Get colors from user input color type."""
220
+ if color_type == "default":
221
+ return _get_default_colors(num_colors)
222
+ elif color_type == "random":
223
+ return _get_random_colors(num_colors)
224
+ else:
225
+ raise ValueError("color_type must be either 'default' or 'random'")
226
+
227
+
228
+ def _get_default_colors(num_colors: int) -> list[Color]:
229
+ """Get `num_colors` of default colors from matplotlib rc params."""
230
+ import matplotlib.pyplot as plt
231
+
232
+ colors = [c["color"] for c in plt.rcParams["axes.prop_cycle"]]
233
+ return colors[0:num_colors]
234
+
235
+
236
+ def _get_random_colors(num_colors: int) -> list[Color]:
237
+ """Get `num_colors` of random colors."""
238
+ return [_random_color(num) for num in range(num_colors)]
239
+
240
+
241
+ def _random_color(column: int) -> list[float]:
242
+ """Get a random color represented as a list of length 3"""
243
+ # GH17525 use common._random_state to avoid resetting the seed
244
+ rs = com.random_state(column)
245
+ return rs.rand(3).tolist()
246
+
247
+
248
+ def _is_single_string_color(color: Color) -> bool:
249
+ """Check if `color` is a single string color.
250
+
251
+ Examples of single string colors:
252
+ - 'r'
253
+ - 'g'
254
+ - 'red'
255
+ - 'green'
256
+ - 'C3'
257
+ - 'firebrick'
258
+
259
+ Parameters
260
+ ----------
261
+ color : Color
262
+ Color string or sequence of floats.
263
+
264
+ Returns
265
+ -------
266
+ bool
267
+ True if `color` looks like a valid color.
268
+ False otherwise.
269
+ """
270
+ conv = matplotlib.colors.ColorConverter()
271
+ try:
272
+ # error: Argument 1 to "to_rgba" of "ColorConverter" has incompatible type
273
+ # "str | Sequence[float]"; expected "tuple[float, float, float] | ..."
274
+ conv.to_rgba(color) # type: ignore[arg-type]
275
+ except ValueError:
276
+ return False
277
+ else:
278
+ return True
venv/lib/python3.10/site-packages/pandas/plotting/_matplotlib/timeseries.py ADDED
@@ -0,0 +1,370 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # TODO: Use the fact that axis can have units to simplify the process
2
+
3
+ from __future__ import annotations
4
+
5
+ import functools
6
+ from typing import (
7
+ TYPE_CHECKING,
8
+ Any,
9
+ cast,
10
+ )
11
+ import warnings
12
+
13
+ import numpy as np
14
+
15
+ from pandas._libs.tslibs import (
16
+ BaseOffset,
17
+ Period,
18
+ to_offset,
19
+ )
20
+ from pandas._libs.tslibs.dtypes import (
21
+ OFFSET_TO_PERIOD_FREQSTR,
22
+ FreqGroup,
23
+ )
24
+
25
+ from pandas.core.dtypes.generic import (
26
+ ABCDatetimeIndex,
27
+ ABCPeriodIndex,
28
+ ABCTimedeltaIndex,
29
+ )
30
+
31
+ from pandas.io.formats.printing import pprint_thing
32
+ from pandas.plotting._matplotlib.converter import (
33
+ TimeSeries_DateFormatter,
34
+ TimeSeries_DateLocator,
35
+ TimeSeries_TimedeltaFormatter,
36
+ )
37
+ from pandas.tseries.frequencies import (
38
+ get_period_alias,
39
+ is_subperiod,
40
+ is_superperiod,
41
+ )
42
+
43
+ if TYPE_CHECKING:
44
+ from datetime import timedelta
45
+
46
+ from matplotlib.axes import Axes
47
+
48
+ from pandas._typing import NDFrameT
49
+
50
+ from pandas import (
51
+ DataFrame,
52
+ DatetimeIndex,
53
+ Index,
54
+ PeriodIndex,
55
+ Series,
56
+ )
57
+
58
+ # ---------------------------------------------------------------------
59
+ # Plotting functions and monkey patches
60
+
61
+
62
+ def maybe_resample(series: Series, ax: Axes, kwargs: dict[str, Any]):
63
+ # resample against axes freq if necessary
64
+
65
+ if "how" in kwargs:
66
+ raise ValueError(
67
+ "'how' is not a valid keyword for plotting functions. If plotting "
68
+ "multiple objects on shared axes, resample manually first."
69
+ )
70
+
71
+ freq, ax_freq = _get_freq(ax, series)
72
+
73
+ if freq is None: # pragma: no cover
74
+ raise ValueError("Cannot use dynamic axis without frequency info")
75
+
76
+ # Convert DatetimeIndex to PeriodIndex
77
+ if isinstance(series.index, ABCDatetimeIndex):
78
+ series = series.to_period(freq=freq)
79
+
80
+ if ax_freq is not None and freq != ax_freq:
81
+ if is_superperiod(freq, ax_freq): # upsample input
82
+ series = series.copy()
83
+ # error: "Index" has no attribute "asfreq"
84
+ series.index = series.index.asfreq( # type: ignore[attr-defined]
85
+ ax_freq, how="s"
86
+ )
87
+ freq = ax_freq
88
+ elif _is_sup(freq, ax_freq): # one is weekly
89
+ # Resampling with PeriodDtype is deprecated, so we convert to
90
+ # DatetimeIndex, resample, then convert back.
91
+ ser_ts = series.to_timestamp()
92
+ ser_d = ser_ts.resample("D").last().dropna()
93
+ ser_freq = ser_d.resample(ax_freq).last().dropna()
94
+ series = ser_freq.to_period(ax_freq)
95
+ freq = ax_freq
96
+ elif is_subperiod(freq, ax_freq) or _is_sub(freq, ax_freq):
97
+ _upsample_others(ax, freq, kwargs)
98
+ else: # pragma: no cover
99
+ raise ValueError("Incompatible frequency conversion")
100
+ return freq, series
101
+
102
+
103
+ def _is_sub(f1: str, f2: str) -> bool:
104
+ return (f1.startswith("W") and is_subperiod("D", f2)) or (
105
+ f2.startswith("W") and is_subperiod(f1, "D")
106
+ )
107
+
108
+
109
+ def _is_sup(f1: str, f2: str) -> bool:
110
+ return (f1.startswith("W") and is_superperiod("D", f2)) or (
111
+ f2.startswith("W") and is_superperiod(f1, "D")
112
+ )
113
+
114
+
115
+ def _upsample_others(ax: Axes, freq: BaseOffset, kwargs: dict[str, Any]) -> None:
116
+ legend = ax.get_legend()
117
+ lines, labels = _replot_ax(ax, freq)
118
+ _replot_ax(ax, freq)
119
+
120
+ other_ax = None
121
+ if hasattr(ax, "left_ax"):
122
+ other_ax = ax.left_ax
123
+ if hasattr(ax, "right_ax"):
124
+ other_ax = ax.right_ax
125
+
126
+ if other_ax is not None:
127
+ rlines, rlabels = _replot_ax(other_ax, freq)
128
+ lines.extend(rlines)
129
+ labels.extend(rlabels)
130
+
131
+ if legend is not None and kwargs.get("legend", True) and len(lines) > 0:
132
+ title: str | None = legend.get_title().get_text()
133
+ if title == "None":
134
+ title = None
135
+ ax.legend(lines, labels, loc="best", title=title)
136
+
137
+
138
+ def _replot_ax(ax: Axes, freq: BaseOffset):
139
+ data = getattr(ax, "_plot_data", None)
140
+
141
+ # clear current axes and data
142
+ # TODO #54485
143
+ ax._plot_data = [] # type: ignore[attr-defined]
144
+ ax.clear()
145
+
146
+ decorate_axes(ax, freq)
147
+
148
+ lines = []
149
+ labels = []
150
+ if data is not None:
151
+ for series, plotf, kwds in data:
152
+ series = series.copy()
153
+ idx = series.index.asfreq(freq, how="S")
154
+ series.index = idx
155
+ # TODO #54485
156
+ ax._plot_data.append((series, plotf, kwds)) # type: ignore[attr-defined]
157
+
158
+ # for tsplot
159
+ if isinstance(plotf, str):
160
+ from pandas.plotting._matplotlib import PLOT_CLASSES
161
+
162
+ plotf = PLOT_CLASSES[plotf]._plot
163
+
164
+ lines.append(plotf(ax, series.index._mpl_repr(), series.values, **kwds)[0])
165
+ labels.append(pprint_thing(series.name))
166
+
167
+ return lines, labels
168
+
169
+
170
+ def decorate_axes(ax: Axes, freq: BaseOffset) -> None:
171
+ """Initialize axes for time-series plotting"""
172
+ if not hasattr(ax, "_plot_data"):
173
+ # TODO #54485
174
+ ax._plot_data = [] # type: ignore[attr-defined]
175
+
176
+ # TODO #54485
177
+ ax.freq = freq # type: ignore[attr-defined]
178
+ xaxis = ax.get_xaxis()
179
+ # TODO #54485
180
+ xaxis.freq = freq # type: ignore[attr-defined]
181
+
182
+
183
+ def _get_ax_freq(ax: Axes):
184
+ """
185
+ Get the freq attribute of the ax object if set.
186
+ Also checks shared axes (eg when using secondary yaxis, sharex=True
187
+ or twinx)
188
+ """
189
+ ax_freq = getattr(ax, "freq", None)
190
+ if ax_freq is None:
191
+ # check for left/right ax in case of secondary yaxis
192
+ if hasattr(ax, "left_ax"):
193
+ ax_freq = getattr(ax.left_ax, "freq", None)
194
+ elif hasattr(ax, "right_ax"):
195
+ ax_freq = getattr(ax.right_ax, "freq", None)
196
+ if ax_freq is None:
197
+ # check if a shared ax (sharex/twinx) has already freq set
198
+ shared_axes = ax.get_shared_x_axes().get_siblings(ax)
199
+ if len(shared_axes) > 1:
200
+ for shared_ax in shared_axes:
201
+ ax_freq = getattr(shared_ax, "freq", None)
202
+ if ax_freq is not None:
203
+ break
204
+ return ax_freq
205
+
206
+
207
+ def _get_period_alias(freq: timedelta | BaseOffset | str) -> str | None:
208
+ if isinstance(freq, BaseOffset):
209
+ freqstr = freq.name
210
+ else:
211
+ freqstr = to_offset(freq, is_period=True).rule_code
212
+
213
+ return get_period_alias(freqstr)
214
+
215
+
216
+ def _get_freq(ax: Axes, series: Series):
217
+ # get frequency from data
218
+ freq = getattr(series.index, "freq", None)
219
+ if freq is None:
220
+ freq = getattr(series.index, "inferred_freq", None)
221
+ freq = to_offset(freq, is_period=True)
222
+
223
+ ax_freq = _get_ax_freq(ax)
224
+
225
+ # use axes freq if no data freq
226
+ if freq is None:
227
+ freq = ax_freq
228
+
229
+ # get the period frequency
230
+ freq = _get_period_alias(freq)
231
+ return freq, ax_freq
232
+
233
+
234
+ def use_dynamic_x(ax: Axes, data: DataFrame | Series) -> bool:
235
+ freq = _get_index_freq(data.index)
236
+ ax_freq = _get_ax_freq(ax)
237
+
238
+ if freq is None: # convert irregular if axes has freq info
239
+ freq = ax_freq
240
+ # do not use tsplot if irregular was plotted first
241
+ elif (ax_freq is None) and (len(ax.get_lines()) > 0):
242
+ return False
243
+
244
+ if freq is None:
245
+ return False
246
+
247
+ freq_str = _get_period_alias(freq)
248
+
249
+ if freq_str is None:
250
+ return False
251
+
252
+ # FIXME: hack this for 0.10.1, creating more technical debt...sigh
253
+ if isinstance(data.index, ABCDatetimeIndex):
254
+ # error: "BaseOffset" has no attribute "_period_dtype_code"
255
+ freq_str = OFFSET_TO_PERIOD_FREQSTR.get(freq_str, freq_str)
256
+ base = to_offset(
257
+ freq_str, is_period=True
258
+ )._period_dtype_code # type: ignore[attr-defined]
259
+ x = data.index
260
+ if base <= FreqGroup.FR_DAY.value:
261
+ return x[:1].is_normalized
262
+ period = Period(x[0], freq_str)
263
+ assert isinstance(period, Period)
264
+ return period.to_timestamp().tz_localize(x.tz) == x[0]
265
+ return True
266
+
267
+
268
+ def _get_index_freq(index: Index) -> BaseOffset | None:
269
+ freq = getattr(index, "freq", None)
270
+ if freq is None:
271
+ freq = getattr(index, "inferred_freq", None)
272
+ if freq == "B":
273
+ # error: "Index" has no attribute "dayofweek"
274
+ weekdays = np.unique(index.dayofweek) # type: ignore[attr-defined]
275
+ if (5 in weekdays) or (6 in weekdays):
276
+ freq = None
277
+
278
+ freq = to_offset(freq)
279
+ return freq
280
+
281
+
282
+ def maybe_convert_index(ax: Axes, data: NDFrameT) -> NDFrameT:
283
+ # tsplot converts automatically, but don't want to convert index
284
+ # over and over for DataFrames
285
+ if isinstance(data.index, (ABCDatetimeIndex, ABCPeriodIndex)):
286
+ freq: str | BaseOffset | None = data.index.freq
287
+
288
+ if freq is None:
289
+ # We only get here for DatetimeIndex
290
+ data.index = cast("DatetimeIndex", data.index)
291
+ freq = data.index.inferred_freq
292
+ freq = to_offset(freq)
293
+
294
+ if freq is None:
295
+ freq = _get_ax_freq(ax)
296
+
297
+ if freq is None:
298
+ raise ValueError("Could not get frequency alias for plotting")
299
+
300
+ freq_str = _get_period_alias(freq)
301
+
302
+ with warnings.catch_warnings():
303
+ # suppress Period[B] deprecation warning
304
+ # TODO: need to find an alternative to this before the deprecation
305
+ # is enforced!
306
+ warnings.filterwarnings(
307
+ "ignore",
308
+ r"PeriodDtype\[B\] is deprecated",
309
+ category=FutureWarning,
310
+ )
311
+
312
+ if isinstance(data.index, ABCDatetimeIndex):
313
+ data = data.tz_localize(None).to_period(freq=freq_str)
314
+ elif isinstance(data.index, ABCPeriodIndex):
315
+ data.index = data.index.asfreq(freq=freq_str)
316
+ return data
317
+
318
+
319
+ # Patch methods for subplot.
320
+
321
+
322
+ def _format_coord(freq, t, y) -> str:
323
+ time_period = Period(ordinal=int(t), freq=freq)
324
+ return f"t = {time_period} y = {y:8f}"
325
+
326
+
327
+ def format_dateaxis(
328
+ subplot, freq: BaseOffset, index: DatetimeIndex | PeriodIndex
329
+ ) -> None:
330
+ """
331
+ Pretty-formats the date axis (x-axis).
332
+
333
+ Major and minor ticks are automatically set for the frequency of the
334
+ current underlying series. As the dynamic mode is activated by
335
+ default, changing the limits of the x axis will intelligently change
336
+ the positions of the ticks.
337
+ """
338
+ from matplotlib import pylab
339
+
340
+ # handle index specific formatting
341
+ # Note: DatetimeIndex does not use this
342
+ # interface. DatetimeIndex uses matplotlib.date directly
343
+ if isinstance(index, ABCPeriodIndex):
344
+ majlocator = TimeSeries_DateLocator(
345
+ freq, dynamic_mode=True, minor_locator=False, plot_obj=subplot
346
+ )
347
+ minlocator = TimeSeries_DateLocator(
348
+ freq, dynamic_mode=True, minor_locator=True, plot_obj=subplot
349
+ )
350
+ subplot.xaxis.set_major_locator(majlocator)
351
+ subplot.xaxis.set_minor_locator(minlocator)
352
+
353
+ majformatter = TimeSeries_DateFormatter(
354
+ freq, dynamic_mode=True, minor_locator=False, plot_obj=subplot
355
+ )
356
+ minformatter = TimeSeries_DateFormatter(
357
+ freq, dynamic_mode=True, minor_locator=True, plot_obj=subplot
358
+ )
359
+ subplot.xaxis.set_major_formatter(majformatter)
360
+ subplot.xaxis.set_minor_formatter(minformatter)
361
+
362
+ # x and y coord info
363
+ subplot.format_coord = functools.partial(_format_coord, freq)
364
+
365
+ elif isinstance(index, ABCTimedeltaIndex):
366
+ subplot.xaxis.set_major_formatter(TimeSeries_TimedeltaFormatter())
367
+ else:
368
+ raise TypeError("index type not supported")
369
+
370
+ pylab.draw_if_interactive()
venv/lib/python3.10/site-packages/pandas/plotting/_matplotlib/tools.py ADDED
@@ -0,0 +1,492 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # being a bit too dynamic
2
+ from __future__ import annotations
3
+
4
+ from math import ceil
5
+ from typing import TYPE_CHECKING
6
+ import warnings
7
+
8
+ from matplotlib import ticker
9
+ import matplotlib.table
10
+ import numpy as np
11
+
12
+ from pandas.util._exceptions import find_stack_level
13
+
14
+ from pandas.core.dtypes.common import is_list_like
15
+ from pandas.core.dtypes.generic import (
16
+ ABCDataFrame,
17
+ ABCIndex,
18
+ ABCSeries,
19
+ )
20
+
21
+ if TYPE_CHECKING:
22
+ from collections.abc import (
23
+ Iterable,
24
+ Sequence,
25
+ )
26
+
27
+ from matplotlib.axes import Axes
28
+ from matplotlib.axis import Axis
29
+ from matplotlib.figure import Figure
30
+ from matplotlib.lines import Line2D
31
+ from matplotlib.table import Table
32
+
33
+ from pandas import (
34
+ DataFrame,
35
+ Series,
36
+ )
37
+
38
+
39
+ def do_adjust_figure(fig: Figure) -> bool:
40
+ """Whether fig has constrained_layout enabled."""
41
+ if not hasattr(fig, "get_constrained_layout"):
42
+ return False
43
+ return not fig.get_constrained_layout()
44
+
45
+
46
+ def maybe_adjust_figure(fig: Figure, *args, **kwargs) -> None:
47
+ """Call fig.subplots_adjust unless fig has constrained_layout enabled."""
48
+ if do_adjust_figure(fig):
49
+ fig.subplots_adjust(*args, **kwargs)
50
+
51
+
52
+ def format_date_labels(ax: Axes, rot) -> None:
53
+ # mini version of autofmt_xdate
54
+ for label in ax.get_xticklabels():
55
+ label.set_horizontalalignment("right")
56
+ label.set_rotation(rot)
57
+ fig = ax.get_figure()
58
+ if fig is not None:
59
+ # should always be a Figure but can technically be None
60
+ maybe_adjust_figure(fig, bottom=0.2)
61
+
62
+
63
+ def table(
64
+ ax, data: DataFrame | Series, rowLabels=None, colLabels=None, **kwargs
65
+ ) -> Table:
66
+ if isinstance(data, ABCSeries):
67
+ data = data.to_frame()
68
+ elif isinstance(data, ABCDataFrame):
69
+ pass
70
+ else:
71
+ raise ValueError("Input data must be DataFrame or Series")
72
+
73
+ if rowLabels is None:
74
+ rowLabels = data.index
75
+
76
+ if colLabels is None:
77
+ colLabels = data.columns
78
+
79
+ cellText = data.values
80
+
81
+ # error: Argument "cellText" to "table" has incompatible type "ndarray[Any,
82
+ # Any]"; expected "Sequence[Sequence[str]] | None"
83
+ return matplotlib.table.table(
84
+ ax,
85
+ cellText=cellText, # type: ignore[arg-type]
86
+ rowLabels=rowLabels,
87
+ colLabels=colLabels,
88
+ **kwargs,
89
+ )
90
+
91
+
92
+ def _get_layout(
93
+ nplots: int,
94
+ layout: tuple[int, int] | None = None,
95
+ layout_type: str = "box",
96
+ ) -> tuple[int, int]:
97
+ if layout is not None:
98
+ if not isinstance(layout, (tuple, list)) or len(layout) != 2:
99
+ raise ValueError("Layout must be a tuple of (rows, columns)")
100
+
101
+ nrows, ncols = layout
102
+
103
+ if nrows == -1 and ncols > 0:
104
+ layout = nrows, ncols = (ceil(nplots / ncols), ncols)
105
+ elif ncols == -1 and nrows > 0:
106
+ layout = nrows, ncols = (nrows, ceil(nplots / nrows))
107
+ elif ncols <= 0 and nrows <= 0:
108
+ msg = "At least one dimension of layout must be positive"
109
+ raise ValueError(msg)
110
+
111
+ if nrows * ncols < nplots:
112
+ raise ValueError(
113
+ f"Layout of {nrows}x{ncols} must be larger than required size {nplots}"
114
+ )
115
+
116
+ return layout
117
+
118
+ if layout_type == "single":
119
+ return (1, 1)
120
+ elif layout_type == "horizontal":
121
+ return (1, nplots)
122
+ elif layout_type == "vertical":
123
+ return (nplots, 1)
124
+
125
+ layouts = {1: (1, 1), 2: (1, 2), 3: (2, 2), 4: (2, 2)}
126
+ try:
127
+ return layouts[nplots]
128
+ except KeyError:
129
+ k = 1
130
+ while k**2 < nplots:
131
+ k += 1
132
+
133
+ if (k - 1) * k >= nplots:
134
+ return k, (k - 1)
135
+ else:
136
+ return k, k
137
+
138
+
139
+ # copied from matplotlib/pyplot.py and modified for pandas.plotting
140
+
141
+
142
+ def create_subplots(
143
+ naxes: int,
144
+ sharex: bool = False,
145
+ sharey: bool = False,
146
+ squeeze: bool = True,
147
+ subplot_kw=None,
148
+ ax=None,
149
+ layout=None,
150
+ layout_type: str = "box",
151
+ **fig_kw,
152
+ ):
153
+ """
154
+ Create a figure with a set of subplots already made.
155
+
156
+ This utility wrapper makes it convenient to create common layouts of
157
+ subplots, including the enclosing figure object, in a single call.
158
+
159
+ Parameters
160
+ ----------
161
+ naxes : int
162
+ Number of required axes. Exceeded axes are set invisible. Default is
163
+ nrows * ncols.
164
+
165
+ sharex : bool
166
+ If True, the X axis will be shared amongst all subplots.
167
+
168
+ sharey : bool
169
+ If True, the Y axis will be shared amongst all subplots.
170
+
171
+ squeeze : bool
172
+
173
+ If True, extra dimensions are squeezed out from the returned axis object:
174
+ - if only one subplot is constructed (nrows=ncols=1), the resulting
175
+ single Axis object is returned as a scalar.
176
+ - for Nx1 or 1xN subplots, the returned object is a 1-d numpy object
177
+ array of Axis objects are returned as numpy 1-d arrays.
178
+ - for NxM subplots with N>1 and M>1 are returned as a 2d array.
179
+
180
+ If False, no squeezing is done: the returned axis object is always
181
+ a 2-d array containing Axis instances, even if it ends up being 1x1.
182
+
183
+ subplot_kw : dict
184
+ Dict with keywords passed to the add_subplot() call used to create each
185
+ subplots.
186
+
187
+ ax : Matplotlib axis object, optional
188
+
189
+ layout : tuple
190
+ Number of rows and columns of the subplot grid.
191
+ If not specified, calculated from naxes and layout_type
192
+
193
+ layout_type : {'box', 'horizontal', 'vertical'}, default 'box'
194
+ Specify how to layout the subplot grid.
195
+
196
+ fig_kw : Other keyword arguments to be passed to the figure() call.
197
+ Note that all keywords not recognized above will be
198
+ automatically included here.
199
+
200
+ Returns
201
+ -------
202
+ fig, ax : tuple
203
+ - fig is the Matplotlib Figure object
204
+ - ax can be either a single axis object or an array of axis objects if
205
+ more than one subplot was created. The dimensions of the resulting array
206
+ can be controlled with the squeeze keyword, see above.
207
+
208
+ Examples
209
+ --------
210
+ x = np.linspace(0, 2*np.pi, 400)
211
+ y = np.sin(x**2)
212
+
213
+ # Just a figure and one subplot
214
+ f, ax = plt.subplots()
215
+ ax.plot(x, y)
216
+ ax.set_title('Simple plot')
217
+
218
+ # Two subplots, unpack the output array immediately
219
+ f, (ax1, ax2) = plt.subplots(1, 2, sharey=True)
220
+ ax1.plot(x, y)
221
+ ax1.set_title('Sharing Y axis')
222
+ ax2.scatter(x, y)
223
+
224
+ # Four polar axes
225
+ plt.subplots(2, 2, subplot_kw=dict(polar=True))
226
+ """
227
+ import matplotlib.pyplot as plt
228
+
229
+ if subplot_kw is None:
230
+ subplot_kw = {}
231
+
232
+ if ax is None:
233
+ fig = plt.figure(**fig_kw)
234
+ else:
235
+ if is_list_like(ax):
236
+ if squeeze:
237
+ ax = flatten_axes(ax)
238
+ if layout is not None:
239
+ warnings.warn(
240
+ "When passing multiple axes, layout keyword is ignored.",
241
+ UserWarning,
242
+ stacklevel=find_stack_level(),
243
+ )
244
+ if sharex or sharey:
245
+ warnings.warn(
246
+ "When passing multiple axes, sharex and sharey "
247
+ "are ignored. These settings must be specified when creating axes.",
248
+ UserWarning,
249
+ stacklevel=find_stack_level(),
250
+ )
251
+ if ax.size == naxes:
252
+ fig = ax.flat[0].get_figure()
253
+ return fig, ax
254
+ else:
255
+ raise ValueError(
256
+ f"The number of passed axes must be {naxes}, the "
257
+ "same as the output plot"
258
+ )
259
+
260
+ fig = ax.get_figure()
261
+ # if ax is passed and a number of subplots is 1, return ax as it is
262
+ if naxes == 1:
263
+ if squeeze:
264
+ return fig, ax
265
+ else:
266
+ return fig, flatten_axes(ax)
267
+ else:
268
+ warnings.warn(
269
+ "To output multiple subplots, the figure containing "
270
+ "the passed axes is being cleared.",
271
+ UserWarning,
272
+ stacklevel=find_stack_level(),
273
+ )
274
+ fig.clear()
275
+
276
+ nrows, ncols = _get_layout(naxes, layout=layout, layout_type=layout_type)
277
+ nplots = nrows * ncols
278
+
279
+ # Create empty object array to hold all axes. It's easiest to make it 1-d
280
+ # so we can just append subplots upon creation, and then
281
+ axarr = np.empty(nplots, dtype=object)
282
+
283
+ # Create first subplot separately, so we can share it if requested
284
+ ax0 = fig.add_subplot(nrows, ncols, 1, **subplot_kw)
285
+
286
+ if sharex:
287
+ subplot_kw["sharex"] = ax0
288
+ if sharey:
289
+ subplot_kw["sharey"] = ax0
290
+ axarr[0] = ax0
291
+
292
+ # Note off-by-one counting because add_subplot uses the MATLAB 1-based
293
+ # convention.
294
+ for i in range(1, nplots):
295
+ kwds = subplot_kw.copy()
296
+ # Set sharex and sharey to None for blank/dummy axes, these can
297
+ # interfere with proper axis limits on the visible axes if
298
+ # they share axes e.g. issue #7528
299
+ if i >= naxes:
300
+ kwds["sharex"] = None
301
+ kwds["sharey"] = None
302
+ ax = fig.add_subplot(nrows, ncols, i + 1, **kwds)
303
+ axarr[i] = ax
304
+
305
+ if naxes != nplots:
306
+ for ax in axarr[naxes:]:
307
+ ax.set_visible(False)
308
+
309
+ handle_shared_axes(axarr, nplots, naxes, nrows, ncols, sharex, sharey)
310
+
311
+ if squeeze:
312
+ # Reshape the array to have the final desired dimension (nrow,ncol),
313
+ # though discarding unneeded dimensions that equal 1. If we only have
314
+ # one subplot, just return it instead of a 1-element array.
315
+ if nplots == 1:
316
+ axes = axarr[0]
317
+ else:
318
+ axes = axarr.reshape(nrows, ncols).squeeze()
319
+ else:
320
+ # returned axis array will be always 2-d, even if nrows=ncols=1
321
+ axes = axarr.reshape(nrows, ncols)
322
+
323
+ return fig, axes
324
+
325
+
326
+ def _remove_labels_from_axis(axis: Axis) -> None:
327
+ for t in axis.get_majorticklabels():
328
+ t.set_visible(False)
329
+
330
+ # set_visible will not be effective if
331
+ # minor axis has NullLocator and NullFormatter (default)
332
+ if isinstance(axis.get_minor_locator(), ticker.NullLocator):
333
+ axis.set_minor_locator(ticker.AutoLocator())
334
+ if isinstance(axis.get_minor_formatter(), ticker.NullFormatter):
335
+ axis.set_minor_formatter(ticker.FormatStrFormatter(""))
336
+ for t in axis.get_minorticklabels():
337
+ t.set_visible(False)
338
+
339
+ axis.get_label().set_visible(False)
340
+
341
+
342
+ def _has_externally_shared_axis(ax1: Axes, compare_axis: str) -> bool:
343
+ """
344
+ Return whether an axis is externally shared.
345
+
346
+ Parameters
347
+ ----------
348
+ ax1 : matplotlib.axes.Axes
349
+ Axis to query.
350
+ compare_axis : str
351
+ `"x"` or `"y"` according to whether the X-axis or Y-axis is being
352
+ compared.
353
+
354
+ Returns
355
+ -------
356
+ bool
357
+ `True` if the axis is externally shared. Otherwise `False`.
358
+
359
+ Notes
360
+ -----
361
+ If two axes with different positions are sharing an axis, they can be
362
+ referred to as *externally* sharing the common axis.
363
+
364
+ If two axes sharing an axis also have the same position, they can be
365
+ referred to as *internally* sharing the common axis (a.k.a twinning).
366
+
367
+ _handle_shared_axes() is only interested in axes externally sharing an
368
+ axis, regardless of whether either of the axes is also internally sharing
369
+ with a third axis.
370
+ """
371
+ if compare_axis == "x":
372
+ axes = ax1.get_shared_x_axes()
373
+ elif compare_axis == "y":
374
+ axes = ax1.get_shared_y_axes()
375
+ else:
376
+ raise ValueError(
377
+ "_has_externally_shared_axis() needs 'x' or 'y' as a second parameter"
378
+ )
379
+
380
+ axes_siblings = axes.get_siblings(ax1)
381
+
382
+ # Retain ax1 and any of its siblings which aren't in the same position as it
383
+ ax1_points = ax1.get_position().get_points()
384
+
385
+ for ax2 in axes_siblings:
386
+ if not np.array_equal(ax1_points, ax2.get_position().get_points()):
387
+ return True
388
+
389
+ return False
390
+
391
+
392
+ def handle_shared_axes(
393
+ axarr: Iterable[Axes],
394
+ nplots: int,
395
+ naxes: int,
396
+ nrows: int,
397
+ ncols: int,
398
+ sharex: bool,
399
+ sharey: bool,
400
+ ) -> None:
401
+ if nplots > 1:
402
+ row_num = lambda x: x.get_subplotspec().rowspan.start
403
+ col_num = lambda x: x.get_subplotspec().colspan.start
404
+
405
+ is_first_col = lambda x: x.get_subplotspec().is_first_col()
406
+
407
+ if nrows > 1:
408
+ try:
409
+ # first find out the ax layout,
410
+ # so that we can correctly handle 'gaps"
411
+ layout = np.zeros((nrows + 1, ncols + 1), dtype=np.bool_)
412
+ for ax in axarr:
413
+ layout[row_num(ax), col_num(ax)] = ax.get_visible()
414
+
415
+ for ax in axarr:
416
+ # only the last row of subplots should get x labels -> all
417
+ # other off layout handles the case that the subplot is
418
+ # the last in the column, because below is no subplot/gap.
419
+ if not layout[row_num(ax) + 1, col_num(ax)]:
420
+ continue
421
+ if sharex or _has_externally_shared_axis(ax, "x"):
422
+ _remove_labels_from_axis(ax.xaxis)
423
+
424
+ except IndexError:
425
+ # if gridspec is used, ax.rowNum and ax.colNum may different
426
+ # from layout shape. in this case, use last_row logic
427
+ is_last_row = lambda x: x.get_subplotspec().is_last_row()
428
+ for ax in axarr:
429
+ if is_last_row(ax):
430
+ continue
431
+ if sharex or _has_externally_shared_axis(ax, "x"):
432
+ _remove_labels_from_axis(ax.xaxis)
433
+
434
+ if ncols > 1:
435
+ for ax in axarr:
436
+ # only the first column should get y labels -> set all other to
437
+ # off as we only have labels in the first column and we always
438
+ # have a subplot there, we can skip the layout test
439
+ if is_first_col(ax):
440
+ continue
441
+ if sharey or _has_externally_shared_axis(ax, "y"):
442
+ _remove_labels_from_axis(ax.yaxis)
443
+
444
+
445
+ def flatten_axes(axes: Axes | Sequence[Axes]) -> np.ndarray:
446
+ if not is_list_like(axes):
447
+ return np.array([axes])
448
+ elif isinstance(axes, (np.ndarray, ABCIndex)):
449
+ return np.asarray(axes).ravel()
450
+ return np.array(axes)
451
+
452
+
453
+ def set_ticks_props(
454
+ axes: Axes | Sequence[Axes],
455
+ xlabelsize: int | None = None,
456
+ xrot=None,
457
+ ylabelsize: int | None = None,
458
+ yrot=None,
459
+ ):
460
+ import matplotlib.pyplot as plt
461
+
462
+ for ax in flatten_axes(axes):
463
+ if xlabelsize is not None:
464
+ plt.setp(ax.get_xticklabels(), fontsize=xlabelsize)
465
+ if xrot is not None:
466
+ plt.setp(ax.get_xticklabels(), rotation=xrot)
467
+ if ylabelsize is not None:
468
+ plt.setp(ax.get_yticklabels(), fontsize=ylabelsize)
469
+ if yrot is not None:
470
+ plt.setp(ax.get_yticklabels(), rotation=yrot)
471
+ return axes
472
+
473
+
474
+ def get_all_lines(ax: Axes) -> list[Line2D]:
475
+ lines = ax.get_lines()
476
+
477
+ if hasattr(ax, "right_ax"):
478
+ lines += ax.right_ax.get_lines()
479
+
480
+ if hasattr(ax, "left_ax"):
481
+ lines += ax.left_ax.get_lines()
482
+
483
+ return lines
484
+
485
+
486
+ def get_xlim(lines: Iterable[Line2D]) -> tuple[float, float]:
487
+ left, right = np.inf, -np.inf
488
+ for line in lines:
489
+ x = line.get_xdata(orig=False)
490
+ left = min(np.nanmin(x), left)
491
+ right = max(np.nanmax(x), right)
492
+ return left, right
venv/lib/python3.10/site-packages/pandas/tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (180 Bytes). View file
 
venv/lib/python3.10/site-packages/pandas/tests/__pycache__/test_aggregation.cpython-310.pyc ADDED
Binary file (3.09 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/__pycache__/test_algos.cpython-310.pyc ADDED
Binary file (60.4 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/__pycache__/test_common.cpython-310.pyc ADDED
Binary file (7.96 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/__pycache__/test_downstream.cpython-310.pyc ADDED
Binary file (9.45 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/__pycache__/test_errors.cpython-310.pyc ADDED
Binary file (3.03 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/__pycache__/test_expressions.cpython-310.pyc ADDED
Binary file (11.8 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/__pycache__/test_flags.cpython-310.pyc ADDED
Binary file (1.9 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/__pycache__/test_multilevel.cpython-310.pyc ADDED
Binary file (10.6 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/__pycache__/test_nanops.cpython-310.pyc ADDED
Binary file (32.8 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/__pycache__/test_optional_dependency.cpython-310.pyc ADDED
Binary file (2.71 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/__pycache__/test_register_accessor.cpython-310.pyc ADDED
Binary file (4.23 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/__pycache__/test_sorting.cpython-310.pyc ADDED
Binary file (14.2 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/__pycache__/test_take.cpython-310.pyc ADDED
Binary file (9.61 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/base/__init__.py ADDED
File without changes
venv/lib/python3.10/site-packages/pandas/tests/base/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (185 Bytes). View file
 
venv/lib/python3.10/site-packages/pandas/tests/base/__pycache__/common.cpython-310.pyc ADDED
Binary file (529 Bytes). View file
 
venv/lib/python3.10/site-packages/pandas/tests/base/__pycache__/test_constructors.cpython-310.pyc ADDED
Binary file (5.6 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/base/__pycache__/test_conversion.cpython-310.pyc ADDED
Binary file (14.3 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/base/__pycache__/test_fillna.cpython-310.pyc ADDED
Binary file (1.56 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/base/__pycache__/test_misc.cpython-310.pyc ADDED
Binary file (5.04 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/base/__pycache__/test_transpose.cpython-310.pyc ADDED
Binary file (1.82 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/base/__pycache__/test_unique.cpython-310.pyc ADDED
Binary file (3.68 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/base/__pycache__/test_value_counts.cpython-310.pyc ADDED
Binary file (8.11 kB). View file