forked from pandas-dev/pandas
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcore.py
2169 lines (1862 loc) · 72 KB
/
core.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
from abc import (
ABC,
abstractmethod,
)
from collections.abc import (
Hashable,
Iterable,
Iterator,
Sequence,
)
from typing import (
TYPE_CHECKING,
Any,
Literal,
cast,
final,
)
import warnings
import matplotlib as mpl
import numpy as np
from pandas._libs import lib
from pandas.errors import AbstractMethodError
from pandas.util._decorators import cache_readonly
from pandas.util._exceptions import find_stack_level
from pandas.core.dtypes.common import (
is_any_real_numeric_dtype,
is_bool,
is_float,
is_float_dtype,
is_hashable,
is_integer,
is_integer_dtype,
is_iterator,
is_list_like,
is_number,
is_numeric_dtype,
)
from pandas.core.dtypes.dtypes import (
CategoricalDtype,
ExtensionDtype,
)
from pandas.core.dtypes.generic import (
ABCDataFrame,
ABCDatetimeIndex,
ABCIndex,
ABCMultiIndex,
ABCPeriodIndex,
ABCSeries,
)
from pandas.core.dtypes.missing import isna
import pandas.core.common as com
from pandas.util.version import Version
from pandas.io.formats.printing import pprint_thing
from pandas.plotting._matplotlib import tools
from pandas.plotting._matplotlib.converter import (
PeriodConverter,
register_pandas_matplotlib_converters,
)
from pandas.plotting._matplotlib.groupby import reconstruct_data_with_by
from pandas.plotting._matplotlib.misc import unpack_single_str_list
from pandas.plotting._matplotlib.style import get_standard_colors
from pandas.plotting._matplotlib.timeseries import (
format_dateaxis,
maybe_convert_index,
prepare_ts_data,
use_dynamic_x,
)
from pandas.plotting._matplotlib.tools import (
create_subplots,
flatten_axes,
format_date_labels,
get_all_lines,
get_xlim,
handle_shared_axes,
)
if TYPE_CHECKING:
from matplotlib.artist import Artist
from matplotlib.axes import Axes
from matplotlib.axis import Axis
from matplotlib.figure import Figure
from pandas._typing import (
IndexLabel,
NDFrameT,
PlottingOrientation,
npt,
)
from pandas import (
DataFrame,
Index,
Series,
)
def holds_integer(column: Index) -> bool:
return column.inferred_type in {"integer", "mixed-integer"}
def _color_in_style(style: str) -> bool:
"""
Check if there is a color letter in the style string.
"""
return not set(mpl.colors.BASE_COLORS).isdisjoint(style)
class MPLPlot(ABC):
"""
Base class for assembling a pandas plot using matplotlib
Parameters
----------
data :
"""
@property
@abstractmethod
def _kind(self) -> str:
"""Specify kind str. Must be overridden in child class"""
raise NotImplementedError
_layout_type = "vertical"
_default_rot = 0
@property
def orientation(self) -> str | None:
return None
data: DataFrame
def __init__(
self,
data,
kind=None,
by: IndexLabel | None = None,
subplots: bool | Sequence[Sequence[str]] = False,
sharex: bool | None = None,
sharey: bool = False,
use_index: bool = True,
figsize: tuple[float, float] | None = None,
grid=None,
legend: bool | str = True,
rot=None,
ax=None,
fig=None,
title=None,
xlim=None,
ylim=None,
xticks=None,
yticks=None,
xlabel: Hashable | None = None,
ylabel: Hashable | None = None,
fontsize: int | None = None,
secondary_y: bool | tuple | list | np.ndarray = False,
colormap=None,
table: bool = False,
layout=None,
include_bool: bool = False,
column: IndexLabel | None = None,
*,
logx: bool | None | Literal["sym"] = False,
logy: bool | None | Literal["sym"] = False,
loglog: bool | None | Literal["sym"] = False,
mark_right: bool = True,
stacked: bool = False,
label: Hashable | None = None,
style=None,
**kwds,
) -> None:
# if users assign an empty list or tuple, raise `ValueError`
# similar to current `df.box` and `df.hist` APIs.
if by in ([], ()):
raise ValueError("No group keys passed!")
self.by = com.maybe_make_list(by)
# Assign the rest of columns into self.columns if by is explicitly defined
# while column is not, only need `columns` in hist/box plot when it's DF
# TODO: Might deprecate `column` argument in future PR (#28373)
if isinstance(data, ABCDataFrame):
if column:
self.columns = com.maybe_make_list(column)
elif self.by is None:
self.columns = [
col for col in data.columns if is_numeric_dtype(data[col])
]
else:
self.columns = [
col
for col in data.columns
if col not in self.by and is_numeric_dtype(data[col])
]
# For `hist` plot, need to get grouped original data before `self.data` is
# updated later
if self.by is not None and self._kind == "hist":
self._grouped = data.groupby(unpack_single_str_list(self.by))
self.kind = kind
self.subplots = type(self)._validate_subplots_kwarg(
subplots, data, kind=self._kind
)
self.sharex = type(self)._validate_sharex(sharex, ax, by)
self.sharey = sharey
self.figsize = figsize
self.layout = layout
self.xticks = xticks
self.yticks = yticks
self.xlim = xlim
self.ylim = ylim
self.title = title
self.use_index = use_index
self.xlabel = xlabel
self.ylabel = ylabel
self.fontsize = fontsize
if rot is not None:
self.rot = rot
# need to know for format_date_labels since it's rotated to 30 by
# default
self._rot_set = True
else:
self._rot_set = False
self.rot = self._default_rot
if grid is None:
grid = False if secondary_y else mpl.rcParams["axes.grid"]
self.grid = grid
self.legend = legend
self.legend_handles: list[Artist] = []
self.legend_labels: list[Hashable] = []
self.logx = type(self)._validate_log_kwd("logx", logx)
self.logy = type(self)._validate_log_kwd("logy", logy)
self.loglog = type(self)._validate_log_kwd("loglog", loglog)
self.label = label
self.style = style
self.mark_right = mark_right
self.stacked = stacked
# ax may be an Axes object or (if self.subplots) an ndarray of
# Axes objects
self.ax = ax
# TODO: deprecate fig keyword as it is ignored, not passed in tests
# as of 2023-11-05
# parse errorbar input if given
xerr = kwds.pop("xerr", None)
yerr = kwds.pop("yerr", None)
nseries = self._get_nseries(data)
xerr, data = type(self)._parse_errorbars("xerr", xerr, data, nseries)
yerr, data = type(self)._parse_errorbars("yerr", yerr, data, nseries)
self.errors = {"xerr": xerr, "yerr": yerr}
self.data = data
if not isinstance(secondary_y, (bool, tuple, list, np.ndarray, ABCIndex)):
secondary_y = [secondary_y]
self.secondary_y = secondary_y
# ugly TypeError if user passes matplotlib's `cmap` name.
# Probably better to accept either.
if "cmap" in kwds and colormap:
raise TypeError("Only specify one of `cmap` and `colormap`.")
if "cmap" in kwds:
self.colormap = kwds.pop("cmap")
else:
self.colormap = colormap
self.table = table
self.include_bool = include_bool
self.kwds = kwds
color = kwds.pop("color", lib.no_default)
self.color = self._validate_color_args(color, self.colormap)
assert "color" not in self.kwds
self.data = self._ensure_frame(self.data)
from pandas.plotting import plot_params
self.x_compat = plot_params["x_compat"]
if "x_compat" in self.kwds:
self.x_compat = bool(self.kwds.pop("x_compat"))
@final
def _is_ts_plot(self) -> bool:
# this is slightly deceptive
return not self.x_compat and self.use_index and self._use_dynamic_x()
@final
def _use_dynamic_x(self) -> bool:
return use_dynamic_x(self._get_ax(0), self.data.index)
@final
@staticmethod
def _validate_sharex(sharex: bool | None, ax, by) -> bool:
if sharex is None:
# if by is defined, subplots are used and sharex should be False
if ax is None and by is None:
sharex = True
else:
# if we get an axis, the users should do the visibility
# setting...
sharex = False
elif not is_bool(sharex):
raise TypeError("sharex must be a bool or None")
return bool(sharex)
@classmethod
def _validate_log_kwd(
cls,
kwd: str,
value: bool | None | Literal["sym"],
) -> bool | None | Literal["sym"]:
if (
value is None
or isinstance(value, bool)
or (isinstance(value, str) and value == "sym")
):
return value
raise ValueError(
f"keyword '{kwd}' should be bool, None, or 'sym', not '{value}'"
)
@final
@staticmethod
def _validate_subplots_kwarg(
subplots: bool | Sequence[Sequence[str]], data: Series | DataFrame, kind: str
) -> bool | list[tuple[int, ...]]:
"""
Validate the subplots parameter
- check type and content
- check for duplicate columns
- check for invalid column names
- convert column names into indices
- add missing columns in a group of their own
See comments in code below for more details.
Parameters
----------
subplots : subplots parameters as passed to PlotAccessor
Returns
-------
validated subplots : a bool or a list of tuples of column indices. Columns
in the same tuple will be grouped together in the resulting plot.
"""
if isinstance(subplots, bool):
return subplots
elif not isinstance(subplots, Iterable):
raise ValueError("subplots should be a bool or an iterable")
supported_kinds = (
"line",
"bar",
"barh",
"hist",
"kde",
"density",
"area",
"pie",
)
if kind not in supported_kinds:
raise ValueError(
"When subplots is an iterable, kind must be "
f"one of {', '.join(supported_kinds)}. Got {kind}."
)
if isinstance(data, ABCSeries):
raise NotImplementedError(
"An iterable subplots for a Series is not supported."
)
columns = data.columns
if isinstance(columns, ABCMultiIndex):
raise NotImplementedError(
"An iterable subplots for a DataFrame with a MultiIndex column "
"is not supported."
)
if columns.nunique() != len(columns):
raise NotImplementedError(
"An iterable subplots for a DataFrame with non-unique column "
"labels is not supported."
)
# subplots is a list of tuples where each tuple is a group of
# columns to be grouped together (one ax per group).
# we consolidate the subplots list such that:
# - the tuples contain indices instead of column names
# - the columns that aren't yet in the list are added in a group
# of their own.
# For example with columns from a to g, and
# subplots = [(a, c), (b, f, e)],
# we end up with [(ai, ci), (bi, fi, ei), (di,), (gi,)]
# This way, we can handle self.subplots in a homogeneous manner
# later.
# TODO: also accept indices instead of just names?
out = []
seen_columns: set[Hashable] = set()
for group in subplots:
if not is_list_like(group):
raise ValueError(
"When subplots is an iterable, each entry "
"should be a list/tuple of column names."
)
idx_locs = columns.get_indexer_for(group)
if (idx_locs == -1).any():
bad_labels = np.extract(idx_locs == -1, group)
raise ValueError(
f"Column label(s) {list(bad_labels)} not found in the DataFrame."
)
unique_columns = set(group)
duplicates = seen_columns.intersection(unique_columns)
if duplicates:
raise ValueError(
"Each column should be in only one subplot. "
f"Columns {duplicates} were found in multiple subplots."
)
seen_columns = seen_columns.union(unique_columns)
out.append(tuple(idx_locs))
unseen_columns = columns.difference(seen_columns)
for column in unseen_columns:
idx_loc = columns.get_loc(column)
out.append((idx_loc,))
return out
def _validate_color_args(self, color, colormap):
if color is lib.no_default:
# It was not provided by the user
if "colors" in self.kwds and colormap is not None:
warnings.warn(
"'color' and 'colormap' cannot be used simultaneously. "
"Using 'color'",
stacklevel=find_stack_level(),
)
return None
if self.nseries == 1 and color is not None and not is_list_like(color):
# support series.plot(color='green')
color = [color]
if isinstance(color, tuple) and self.nseries == 1 and len(color) in (3, 4):
# support RGB and RGBA tuples in series plot
color = [color]
if colormap is not None:
warnings.warn(
"'color' and 'colormap' cannot be used simultaneously. Using 'color'",
stacklevel=find_stack_level(),
)
if self.style is not None:
if isinstance(self.style, dict):
styles = [self.style[col] for col in self.columns if col in self.style]
elif is_list_like(self.style):
styles = self.style
else:
styles = [self.style]
# need only a single match
for s in styles:
if _color_in_style(s):
raise ValueError(
"Cannot pass 'style' string with a color symbol and "
"'color' keyword argument. Please use one or the "
"other or pass 'style' without a color symbol"
)
return color
@final
@staticmethod
def _iter_data(
data: DataFrame | dict[Hashable, Series | DataFrame],
) -> Iterator[tuple[Hashable, np.ndarray]]:
for col, values in data.items():
# This was originally written to use values.values before EAs
# were implemented; adding np.asarray(...) to keep consistent
# typing.
yield col, np.asarray(values.values)
def _get_nseries(self, data: Series | DataFrame) -> int:
# When `by` is explicitly assigned, grouped data size will be defined, and
# this will determine number of subplots to have, aka `self.nseries`
if data.ndim == 1:
return 1
elif self.by is not None and self._kind == "hist":
return len(self._grouped)
elif self.by is not None and self._kind == "box":
return len(self.columns)
else:
return data.shape[1]
@final
@property
def nseries(self) -> int:
return self._get_nseries(self.data)
@final
def generate(self) -> None:
self._compute_plot_data()
fig = self.fig
self._make_plot(fig)
self._add_table()
self._make_legend()
self._adorn_subplots(fig)
for ax in self.axes:
self._post_plot_logic_common(ax)
self._post_plot_logic(ax, self.data)
@final
@staticmethod
def _has_plotted_object(ax: Axes) -> bool:
"""check whether ax has data"""
return len(ax.lines) != 0 or len(ax.artists) != 0 or len(ax.containers) != 0
@final
def _maybe_right_yaxis(self, ax: Axes, axes_num: int) -> Axes:
if not self.on_right(axes_num):
# secondary axes may be passed via ax kw
return self._get_ax_layer(ax)
if hasattr(ax, "right_ax"):
# if it has right_ax property, ``ax`` must be left axes
return ax.right_ax
elif hasattr(ax, "left_ax"):
# if it has left_ax property, ``ax`` must be right axes
return ax
else:
# otherwise, create twin axes
orig_ax, new_ax = ax, ax.twinx()
# TODO: use Matplotlib public API when available
new_ax._get_lines = orig_ax._get_lines # type: ignore[attr-defined]
# TODO #54485
new_ax._get_patches_for_fill = ( # type: ignore[attr-defined]
orig_ax._get_patches_for_fill # type: ignore[attr-defined]
)
# TODO #54485
orig_ax.right_ax, new_ax.left_ax = ( # type: ignore[attr-defined]
new_ax,
orig_ax,
)
if not self._has_plotted_object(orig_ax): # no data on left y
orig_ax.get_yaxis().set_visible(False)
if self.logy is True or self.loglog is True:
new_ax.set_yscale("log")
elif self.logy == "sym" or self.loglog == "sym":
new_ax.set_yscale("symlog")
return new_ax
@final
@cache_readonly
def fig(self) -> Figure:
return self._axes_and_fig[1]
@final
@cache_readonly
# TODO: can we annotate this as both a Sequence[Axes] and ndarray[object]?
def axes(self) -> Sequence[Axes]:
return self._axes_and_fig[0]
@final
@cache_readonly
def _axes_and_fig(self) -> tuple[Sequence[Axes], Figure]:
import matplotlib.pyplot as plt
if self.subplots:
naxes = (
self.nseries if isinstance(self.subplots, bool) else len(self.subplots)
)
fig, axes = create_subplots(
naxes=naxes,
sharex=self.sharex,
sharey=self.sharey,
figsize=self.figsize,
ax=self.ax,
layout=self.layout,
layout_type=self._layout_type,
)
elif self.ax is None:
fig = plt.figure(figsize=self.figsize)
axes = fig.add_subplot(111)
else:
fig = self.ax.get_figure()
if self.figsize is not None:
fig.set_size_inches(self.figsize)
axes = self.ax
axes = np.fromiter(flatten_axes(axes), dtype=object)
if self.logx is True or self.loglog is True:
[a.set_xscale("log") for a in axes]
elif self.logx == "sym" or self.loglog == "sym":
[a.set_xscale("symlog") for a in axes]
if self.logy is True or self.loglog is True:
[a.set_yscale("log") for a in axes]
elif self.logy == "sym" or self.loglog == "sym":
[a.set_yscale("symlog") for a in axes]
axes_seq = cast(Sequence["Axes"], axes)
return axes_seq, fig
@property
def result(self):
"""
Return result axes
"""
if self.subplots:
if self.layout is not None and not is_list_like(self.ax):
# error: "Sequence[Any]" has no attribute "reshape"
return self.axes.reshape(*self.layout) # type: ignore[attr-defined]
else:
return self.axes
else:
sec_true = isinstance(self.secondary_y, bool) and self.secondary_y
# error: Argument 1 to "len" has incompatible type "Union[bool,
# Tuple[Any, ...], List[Any], ndarray[Any, Any]]"; expected "Sized"
all_sec = (
is_list_like(self.secondary_y) and len(self.secondary_y) == self.nseries # type: ignore[arg-type]
)
if sec_true or all_sec:
# if all data is plotted on secondary, return right axes
return self._get_ax_layer(self.axes[0], primary=False)
else:
return self.axes[0]
@final
@staticmethod
def _convert_to_ndarray(data):
# GH31357: categorical columns are processed separately
if isinstance(data.dtype, CategoricalDtype):
return data
# GH32073: cast to float if values contain nulled integers
if (is_integer_dtype(data.dtype) or is_float_dtype(data.dtype)) and isinstance(
data.dtype, ExtensionDtype
):
return data.to_numpy(dtype="float", na_value=np.nan)
# GH25587: cast ExtensionArray of pandas (IntegerArray, etc.) to
# np.ndarray before plot.
if len(data) > 0:
return np.asarray(data)
return data
@final
def _ensure_frame(self, data) -> DataFrame:
if isinstance(data, ABCSeries):
label = self.label
if label is None and data.name is None:
label = ""
if label is None:
# We'll end up with columns of [0] instead of [None]
data = data.to_frame()
else:
data = data.to_frame(name=label)
elif self._kind in ("hist", "box"):
cols = self.columns if self.by is None else self.columns + self.by
data = data.loc[:, cols]
return data
@final
def _compute_plot_data(self) -> None:
data = self.data
# GH15079 reconstruct data if by is defined
if self.by is not None:
self.subplots = True
data = reconstruct_data_with_by(self.data, by=self.by, cols=self.columns)
# GH16953, infer_objects is needed as fallback, for ``Series``
# with ``dtype == object``
data = data.infer_objects()
include_type = [np.number, "datetime", "datetimetz", "timedelta"]
# GH23719, allow plotting boolean
if self.include_bool is True:
include_type.append(np.bool_)
# GH22799, exclude datetime-like type for boxplot
exclude_type = None
if self._kind == "box":
# TODO: change after solving issue 27881
include_type = [np.number]
exclude_type = ["timedelta"]
# GH 18755, include object and category type for scatter plot
if self._kind == "scatter":
include_type.extend(["object", "category", "string"])
numeric_data = data.select_dtypes(include=include_type, exclude=exclude_type)
is_empty = numeric_data.shape[-1] == 0
# no non-numeric frames or series allowed
if is_empty:
raise TypeError("no numeric data to plot")
self.data = numeric_data.apply(type(self)._convert_to_ndarray)
def _make_plot(self, fig: Figure) -> None:
raise AbstractMethodError(self)
@final
def _add_table(self) -> None:
if self.table is False:
return
elif self.table is True:
data = self.data.transpose()
else:
data = self.table
ax = self._get_ax(0)
tools.table(ax, data)
@final
def _post_plot_logic_common(self, ax: Axes) -> None:
"""Common post process for each axes"""
if self.orientation == "vertical" or self.orientation is None:
type(self)._apply_axis_properties(
ax.xaxis, rot=self.rot, fontsize=self.fontsize
)
type(self)._apply_axis_properties(ax.yaxis, fontsize=self.fontsize)
if hasattr(ax, "right_ax"):
type(self)._apply_axis_properties(
ax.right_ax.yaxis, fontsize=self.fontsize
)
elif self.orientation == "horizontal":
type(self)._apply_axis_properties(
ax.yaxis, rot=self.rot, fontsize=self.fontsize
)
type(self)._apply_axis_properties(ax.xaxis, fontsize=self.fontsize)
if hasattr(ax, "right_ax"):
type(self)._apply_axis_properties(
ax.right_ax.yaxis, fontsize=self.fontsize
)
else: # pragma no cover
raise ValueError
@abstractmethod
def _post_plot_logic(self, ax: Axes, data) -> None:
"""Post process for each axes. Overridden in child classes"""
@final
def _adorn_subplots(self, fig: Figure) -> None:
"""Common post process unrelated to data"""
if len(self.axes) > 0:
all_axes = self._get_subplots(fig)
nrows, ncols = self._get_axes_layout(fig)
handle_shared_axes(
axarr=all_axes,
nplots=len(all_axes),
naxes=nrows * ncols,
nrows=nrows,
ncols=ncols,
sharex=self.sharex,
sharey=self.sharey,
)
for ax in self.axes:
ax = getattr(ax, "right_ax", ax)
if self.yticks is not None:
ax.set_yticks(self.yticks)
if self.xticks is not None:
ax.set_xticks(self.xticks)
if self.ylim is not None:
ax.set_ylim(self.ylim)
if self.xlim is not None:
ax.set_xlim(self.xlim)
# GH9093, currently Pandas does not show ylabel, so if users provide
# ylabel will set it as ylabel in the plot.
if self.ylabel is not None:
ax.set_ylabel(pprint_thing(self.ylabel))
ax.grid(self.grid)
if self.title:
if self.subplots:
if is_list_like(self.title):
if len(self.title) != self.nseries:
raise ValueError(
"The length of `title` must equal the number "
"of columns if using `title` of type `list` "
"and `subplots=True`.\n"
f"length of title = {len(self.title)}\n"
f"number of columns = {self.nseries}"
)
for ax, title in zip(self.axes, self.title):
ax.set_title(title)
else:
fig.suptitle(self.title)
else:
if is_list_like(self.title):
msg = (
"Using `title` of type `list` is not supported "
"unless `subplots=True` is passed"
)
raise ValueError(msg)
self.axes[0].set_title(self.title)
@final
@staticmethod
def _apply_axis_properties(
axis: Axis, rot=None, fontsize: int | None = None
) -> None:
"""
Tick creation within matplotlib is reasonably expensive and is
internally deferred until accessed as Ticks are created/destroyed
multiple times per draw. It's therefore beneficial for us to avoid
accessing unless we will act on the Tick.
"""
if rot is not None or fontsize is not None:
# rot=0 is a valid setting, hence the explicit None check
labels = axis.get_majorticklabels() + axis.get_minorticklabels()
for label in labels:
if rot is not None:
label.set_rotation(rot)
if fontsize is not None:
label.set_fontsize(fontsize)
@final
@property
def legend_title(self) -> str | None:
if not isinstance(self.data.columns, ABCMultiIndex):
name = self.data.columns.name
if name is not None:
name = pprint_thing(name)
return name
else:
stringified = map(pprint_thing, self.data.columns.names)
return ",".join(stringified)
@final
def _mark_right_label(self, label: str, index: int) -> str:
"""
Append ``(right)`` to the label of a line if it's plotted on the right axis.
Note that ``(right)`` is only appended when ``subplots=False``.
"""
if not self.subplots and self.mark_right and self.on_right(index):
label += " (right)"
return label
@final
def _append_legend_handles_labels(self, handle: Artist, label: str) -> None:
"""
Append current handle and label to ``legend_handles`` and ``legend_labels``.
These will be used to make the legend.
"""
self.legend_handles.append(handle)
self.legend_labels.append(label)
def _make_legend(self) -> None:
ax, leg = self._get_ax_legend(self.axes[0])
handles = []
labels = []
title = ""
if not self.subplots:
if leg is not None:
title = leg.get_title().get_text()
# Replace leg.legend_handles because it misses marker info
if Version(mpl.__version__) < Version("3.7"):
handles = leg.legendHandles
else:
handles = leg.legend_handles
labels = [x.get_text() for x in leg.get_texts()]
if self.legend:
if self.legend == "reverse":
handles += reversed(self.legend_handles)
labels += reversed(self.legend_labels)
else:
handles += self.legend_handles
labels += self.legend_labels
if self.legend_title is not None:
title = self.legend_title
if len(handles) > 0:
ax.legend(handles, labels, loc="best", title=title)
elif self.subplots and self.legend:
for ax in self.axes:
if ax.get_visible():
with warnings.catch_warnings():
warnings.filterwarnings(
"ignore",
"No artists with labels found to put in legend.",
UserWarning,
)
ax.legend(loc="best")
@final
@staticmethod
def _get_ax_legend(ax: Axes):
"""
Take in axes and return ax and legend under different scenarios
"""
leg = ax.get_legend()
other_ax = getattr(ax, "left_ax", None) or getattr(ax, "right_ax", None)
other_leg = None
if other_ax is not None:
other_leg = other_ax.get_legend()
if leg is None and other_leg is not None:
leg = other_leg
ax = other_ax
return ax, leg
_need_to_set_index = False
@final
def _get_xticks(self):
index = self.data.index
is_datetype = index.inferred_type in ("datetime", "date", "datetime64", "time")
# TODO: be stricter about x?
x: list[int] | np.ndarray
if self.use_index:
if isinstance(index, ABCPeriodIndex):
# test_mixed_freq_irreg_period
x = index.to_timestamp()._mpl_repr()
# TODO: why do we need to do to_timestamp() here but not other
# places where we call mpl_repr?
elif is_any_real_numeric_dtype(index.dtype):
# Matplotlib supports numeric values or datetime objects as
# xaxis values. Taking LBYL approach here, by the time
# matplotlib raises exception when using non numeric/datetime
# values for xaxis, several actions are already taken by plt.
x = index._mpl_repr()
elif isinstance(index, ABCDatetimeIndex) or is_datetype:
x = index._mpl_repr()
else:
self._need_to_set_index = True
x = list(range(len(index)))
else:
x = list(range(len(index)))
return x
@classmethod
@register_pandas_matplotlib_converters
def _plot(
cls, ax: Axes, x, y: np.ndarray, style=None, is_errorbar: bool = False, **kwds
):
mask = isna(y)
if mask.any():
y = np.ma.array(y)
y = np.ma.masked_where(mask, y)
if isinstance(x, ABCIndex):
x = x._mpl_repr()
if is_errorbar:
if "xerr" in kwds:
kwds["xerr"] = np.array(kwds.get("xerr"))
if "yerr" in kwds:
kwds["yerr"] = np.array(kwds.get("yerr"))
return ax.errorbar(x, y, **kwds)
else:
# prevent style kwarg from going to errorbar, where it is unsupported
args = (x, y, style) if style is not None else (x, y)
return ax.plot(*args, **kwds)
def _get_custom_index_name(self):
"""Specify whether xlabel/ylabel should be used to override index name"""
return self.xlabel
@final
def _get_index_name(self) -> str | None: