tools.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492
  1. # being a bit too dynamic
  2. from __future__ import annotations
  3. from math import ceil
  4. from typing import TYPE_CHECKING
  5. import warnings
  6. from matplotlib import ticker
  7. import matplotlib.table
  8. import numpy as np
  9. from pandas.util._exceptions import find_stack_level
  10. from pandas.core.dtypes.common import is_list_like
  11. from pandas.core.dtypes.generic import (
  12. ABCDataFrame,
  13. ABCIndex,
  14. ABCSeries,
  15. )
  16. if TYPE_CHECKING:
  17. from collections.abc import (
  18. Iterable,
  19. Sequence,
  20. )
  21. from matplotlib.axes import Axes
  22. from matplotlib.axis import Axis
  23. from matplotlib.figure import Figure
  24. from matplotlib.lines import Line2D
  25. from matplotlib.table import Table
  26. from pandas import (
  27. DataFrame,
  28. Series,
  29. )
  30. def do_adjust_figure(fig: Figure) -> bool:
  31. """Whether fig has constrained_layout enabled."""
  32. if not hasattr(fig, "get_constrained_layout"):
  33. return False
  34. return not fig.get_constrained_layout()
  35. def maybe_adjust_figure(fig: Figure, *args, **kwargs) -> None:
  36. """Call fig.subplots_adjust unless fig has constrained_layout enabled."""
  37. if do_adjust_figure(fig):
  38. fig.subplots_adjust(*args, **kwargs)
  39. def format_date_labels(ax: Axes, rot) -> None:
  40. # mini version of autofmt_xdate
  41. for label in ax.get_xticklabels():
  42. label.set_horizontalalignment("right")
  43. label.set_rotation(rot)
  44. fig = ax.get_figure()
  45. if fig is not None:
  46. # should always be a Figure but can technically be None
  47. maybe_adjust_figure(fig, bottom=0.2) # type: ignore[arg-type]
  48. def table(
  49. ax, data: DataFrame | Series, rowLabels=None, colLabels=None, **kwargs
  50. ) -> Table:
  51. if isinstance(data, ABCSeries):
  52. data = data.to_frame()
  53. elif isinstance(data, ABCDataFrame):
  54. pass
  55. else:
  56. raise ValueError("Input data must be DataFrame or Series")
  57. if rowLabels is None:
  58. rowLabels = data.index
  59. if colLabels is None:
  60. colLabels = data.columns
  61. cellText = data.values
  62. # error: Argument "cellText" to "table" has incompatible type "ndarray[Any,
  63. # Any]"; expected "Sequence[Sequence[str]] | None"
  64. return matplotlib.table.table(
  65. ax,
  66. cellText=cellText, # type: ignore[arg-type]
  67. rowLabels=rowLabels,
  68. colLabels=colLabels,
  69. **kwargs,
  70. )
  71. def _get_layout(
  72. nplots: int,
  73. layout: tuple[int, int] | None = None,
  74. layout_type: str = "box",
  75. ) -> tuple[int, int]:
  76. if layout is not None:
  77. if not isinstance(layout, (tuple, list)) or len(layout) != 2:
  78. raise ValueError("Layout must be a tuple of (rows, columns)")
  79. nrows, ncols = layout
  80. if nrows == -1 and ncols > 0:
  81. layout = nrows, ncols = (ceil(nplots / ncols), ncols)
  82. elif ncols == -1 and nrows > 0:
  83. layout = nrows, ncols = (nrows, ceil(nplots / nrows))
  84. elif ncols <= 0 and nrows <= 0:
  85. msg = "At least one dimension of layout must be positive"
  86. raise ValueError(msg)
  87. if nrows * ncols < nplots:
  88. raise ValueError(
  89. f"Layout of {nrows}x{ncols} must be larger than required size {nplots}"
  90. )
  91. return layout
  92. if layout_type == "single":
  93. return (1, 1)
  94. elif layout_type == "horizontal":
  95. return (1, nplots)
  96. elif layout_type == "vertical":
  97. return (nplots, 1)
  98. layouts = {1: (1, 1), 2: (1, 2), 3: (2, 2), 4: (2, 2)}
  99. try:
  100. return layouts[nplots]
  101. except KeyError:
  102. k = 1
  103. while k**2 < nplots:
  104. k += 1
  105. if (k - 1) * k >= nplots:
  106. return k, (k - 1)
  107. else:
  108. return k, k
  109. # copied from matplotlib/pyplot.py and modified for pandas.plotting
  110. def create_subplots(
  111. naxes: int,
  112. sharex: bool = False,
  113. sharey: bool = False,
  114. squeeze: bool = True,
  115. subplot_kw=None,
  116. ax=None,
  117. layout=None,
  118. layout_type: str = "box",
  119. **fig_kw,
  120. ):
  121. """
  122. Create a figure with a set of subplots already made.
  123. This utility wrapper makes it convenient to create common layouts of
  124. subplots, including the enclosing figure object, in a single call.
  125. Parameters
  126. ----------
  127. naxes : int
  128. Number of required axes. Exceeded axes are set invisible. Default is
  129. nrows * ncols.
  130. sharex : bool
  131. If True, the X axis will be shared amongst all subplots.
  132. sharey : bool
  133. If True, the Y axis will be shared amongst all subplots.
  134. squeeze : bool
  135. If True, extra dimensions are squeezed out from the returned axis object:
  136. - if only one subplot is constructed (nrows=ncols=1), the resulting
  137. single Axis object is returned as a scalar.
  138. - for Nx1 or 1xN subplots, the returned object is a 1-d numpy object
  139. array of Axis objects are returned as numpy 1-d arrays.
  140. - for NxM subplots with N>1 and M>1 are returned as a 2d array.
  141. If False, no squeezing is done: the returned axis object is always
  142. a 2-d array containing Axis instances, even if it ends up being 1x1.
  143. subplot_kw : dict
  144. Dict with keywords passed to the add_subplot() call used to create each
  145. subplots.
  146. ax : Matplotlib axis object, optional
  147. layout : tuple
  148. Number of rows and columns of the subplot grid.
  149. If not specified, calculated from naxes and layout_type
  150. layout_type : {'box', 'horizontal', 'vertical'}, default 'box'
  151. Specify how to layout the subplot grid.
  152. fig_kw : Other keyword arguments to be passed to the figure() call.
  153. Note that all keywords not recognized above will be
  154. automatically included here.
  155. Returns
  156. -------
  157. fig, ax : tuple
  158. - fig is the Matplotlib Figure object
  159. - ax can be either a single axis object or an array of axis objects if
  160. more than one subplot was created. The dimensions of the resulting array
  161. can be controlled with the squeeze keyword, see above.
  162. Examples
  163. --------
  164. x = np.linspace(0, 2*np.pi, 400)
  165. y = np.sin(x**2)
  166. # Just a figure and one subplot
  167. f, ax = plt.subplots()
  168. ax.plot(x, y)
  169. ax.set_title('Simple plot')
  170. # Two subplots, unpack the output array immediately
  171. f, (ax1, ax2) = plt.subplots(1, 2, sharey=True)
  172. ax1.plot(x, y)
  173. ax1.set_title('Sharing Y axis')
  174. ax2.scatter(x, y)
  175. # Four polar axes
  176. plt.subplots(2, 2, subplot_kw=dict(polar=True))
  177. """
  178. import matplotlib.pyplot as plt
  179. if subplot_kw is None:
  180. subplot_kw = {}
  181. if ax is None:
  182. fig = plt.figure(**fig_kw)
  183. else:
  184. if is_list_like(ax):
  185. if squeeze:
  186. ax = flatten_axes(ax)
  187. if layout is not None:
  188. warnings.warn(
  189. "When passing multiple axes, layout keyword is ignored.",
  190. UserWarning,
  191. stacklevel=find_stack_level(),
  192. )
  193. if sharex or sharey:
  194. warnings.warn(
  195. "When passing multiple axes, sharex and sharey "
  196. "are ignored. These settings must be specified when creating axes.",
  197. UserWarning,
  198. stacklevel=find_stack_level(),
  199. )
  200. if ax.size == naxes:
  201. fig = ax.flat[0].get_figure()
  202. return fig, ax
  203. else:
  204. raise ValueError(
  205. f"The number of passed axes must be {naxes}, the "
  206. "same as the output plot"
  207. )
  208. fig = ax.get_figure()
  209. # if ax is passed and a number of subplots is 1, return ax as it is
  210. if naxes == 1:
  211. if squeeze:
  212. return fig, ax
  213. else:
  214. return fig, flatten_axes(ax)
  215. else:
  216. warnings.warn(
  217. "To output multiple subplots, the figure containing "
  218. "the passed axes is being cleared.",
  219. UserWarning,
  220. stacklevel=find_stack_level(),
  221. )
  222. fig.clear()
  223. nrows, ncols = _get_layout(naxes, layout=layout, layout_type=layout_type)
  224. nplots = nrows * ncols
  225. # Create empty object array to hold all axes. It's easiest to make it 1-d
  226. # so we can just append subplots upon creation, and then
  227. axarr = np.empty(nplots, dtype=object)
  228. # Create first subplot separately, so we can share it if requested
  229. ax0 = fig.add_subplot(nrows, ncols, 1, **subplot_kw)
  230. if sharex:
  231. subplot_kw["sharex"] = ax0
  232. if sharey:
  233. subplot_kw["sharey"] = ax0
  234. axarr[0] = ax0
  235. # Note off-by-one counting because add_subplot uses the MATLAB 1-based
  236. # convention.
  237. for i in range(1, nplots):
  238. kwds = subplot_kw.copy()
  239. # Set sharex and sharey to None for blank/dummy axes, these can
  240. # interfere with proper axis limits on the visible axes if
  241. # they share axes e.g. issue #7528
  242. if i >= naxes:
  243. kwds["sharex"] = None
  244. kwds["sharey"] = None
  245. ax = fig.add_subplot(nrows, ncols, i + 1, **kwds)
  246. axarr[i] = ax
  247. if naxes != nplots:
  248. for ax in axarr[naxes:]:
  249. ax.set_visible(False)
  250. handle_shared_axes(axarr, nplots, naxes, nrows, ncols, sharex, sharey)
  251. if squeeze:
  252. # Reshape the array to have the final desired dimension (nrow,ncol),
  253. # though discarding unneeded dimensions that equal 1. If we only have
  254. # one subplot, just return it instead of a 1-element array.
  255. if nplots == 1:
  256. axes = axarr[0]
  257. else:
  258. axes = axarr.reshape(nrows, ncols).squeeze()
  259. else:
  260. # returned axis array will be always 2-d, even if nrows=ncols=1
  261. axes = axarr.reshape(nrows, ncols)
  262. return fig, axes
  263. def _remove_labels_from_axis(axis: Axis) -> None:
  264. for t in axis.get_majorticklabels():
  265. t.set_visible(False)
  266. # set_visible will not be effective if
  267. # minor axis has NullLocator and NullFormatter (default)
  268. if isinstance(axis.get_minor_locator(), ticker.NullLocator):
  269. axis.set_minor_locator(ticker.AutoLocator())
  270. if isinstance(axis.get_minor_formatter(), ticker.NullFormatter):
  271. axis.set_minor_formatter(ticker.FormatStrFormatter(""))
  272. for t in axis.get_minorticklabels():
  273. t.set_visible(False)
  274. axis.get_label().set_visible(False)
  275. def _has_externally_shared_axis(ax1: Axes, compare_axis: str) -> bool:
  276. """
  277. Return whether an axis is externally shared.
  278. Parameters
  279. ----------
  280. ax1 : matplotlib.axes.Axes
  281. Axis to query.
  282. compare_axis : str
  283. `"x"` or `"y"` according to whether the X-axis or Y-axis is being
  284. compared.
  285. Returns
  286. -------
  287. bool
  288. `True` if the axis is externally shared. Otherwise `False`.
  289. Notes
  290. -----
  291. If two axes with different positions are sharing an axis, they can be
  292. referred to as *externally* sharing the common axis.
  293. If two axes sharing an axis also have the same position, they can be
  294. referred to as *internally* sharing the common axis (a.k.a twinning).
  295. _handle_shared_axes() is only interested in axes externally sharing an
  296. axis, regardless of whether either of the axes is also internally sharing
  297. with a third axis.
  298. """
  299. if compare_axis == "x":
  300. axes = ax1.get_shared_x_axes()
  301. elif compare_axis == "y":
  302. axes = ax1.get_shared_y_axes()
  303. else:
  304. raise ValueError(
  305. "_has_externally_shared_axis() needs 'x' or 'y' as a second parameter"
  306. )
  307. axes_siblings = axes.get_siblings(ax1)
  308. # Retain ax1 and any of its siblings which aren't in the same position as it
  309. ax1_points = ax1.get_position().get_points()
  310. for ax2 in axes_siblings:
  311. if not np.array_equal(ax1_points, ax2.get_position().get_points()):
  312. return True
  313. return False
  314. def handle_shared_axes(
  315. axarr: Iterable[Axes],
  316. nplots: int,
  317. naxes: int,
  318. nrows: int,
  319. ncols: int,
  320. sharex: bool,
  321. sharey: bool,
  322. ) -> None:
  323. if nplots > 1:
  324. row_num = lambda x: x.get_subplotspec().rowspan.start
  325. col_num = lambda x: x.get_subplotspec().colspan.start
  326. is_first_col = lambda x: x.get_subplotspec().is_first_col()
  327. if nrows > 1:
  328. try:
  329. # first find out the ax layout,
  330. # so that we can correctly handle 'gaps"
  331. layout = np.zeros((nrows + 1, ncols + 1), dtype=np.bool_)
  332. for ax in axarr:
  333. layout[row_num(ax), col_num(ax)] = ax.get_visible()
  334. for ax in axarr:
  335. # only the last row of subplots should get x labels -> all
  336. # other off layout handles the case that the subplot is
  337. # the last in the column, because below is no subplot/gap.
  338. if not layout[row_num(ax) + 1, col_num(ax)]:
  339. continue
  340. if sharex or _has_externally_shared_axis(ax, "x"):
  341. _remove_labels_from_axis(ax.xaxis)
  342. except IndexError:
  343. # if gridspec is used, ax.rowNum and ax.colNum may different
  344. # from layout shape. in this case, use last_row logic
  345. is_last_row = lambda x: x.get_subplotspec().is_last_row()
  346. for ax in axarr:
  347. if is_last_row(ax):
  348. continue
  349. if sharex or _has_externally_shared_axis(ax, "x"):
  350. _remove_labels_from_axis(ax.xaxis)
  351. if ncols > 1:
  352. for ax in axarr:
  353. # only the first column should get y labels -> set all other to
  354. # off as we only have labels in the first column and we always
  355. # have a subplot there, we can skip the layout test
  356. if is_first_col(ax):
  357. continue
  358. if sharey or _has_externally_shared_axis(ax, "y"):
  359. _remove_labels_from_axis(ax.yaxis)
  360. def flatten_axes(axes: Axes | Sequence[Axes]) -> np.ndarray:
  361. if not is_list_like(axes):
  362. return np.array([axes])
  363. elif isinstance(axes, (np.ndarray, ABCIndex)):
  364. return np.asarray(axes).ravel()
  365. return np.array(axes)
  366. def set_ticks_props(
  367. axes: Axes | Sequence[Axes],
  368. xlabelsize: int | None = None,
  369. xrot=None,
  370. ylabelsize: int | None = None,
  371. yrot=None,
  372. ):
  373. import matplotlib.pyplot as plt
  374. for ax in flatten_axes(axes):
  375. if xlabelsize is not None:
  376. plt.setp(ax.get_xticklabels(), fontsize=xlabelsize)
  377. if xrot is not None:
  378. plt.setp(ax.get_xticklabels(), rotation=xrot)
  379. if ylabelsize is not None:
  380. plt.setp(ax.get_yticklabels(), fontsize=ylabelsize)
  381. if yrot is not None:
  382. plt.setp(ax.get_yticklabels(), rotation=yrot)
  383. return axes
  384. def get_all_lines(ax: Axes) -> list[Line2D]:
  385. lines = ax.get_lines()
  386. if hasattr(ax, "right_ax"):
  387. lines += ax.right_ax.get_lines()
  388. if hasattr(ax, "left_ax"):
  389. lines += ax.left_ax.get_lines()
  390. return lines
  391. def get_xlim(lines: Iterable[Line2D]) -> tuple[float, float]:
  392. left, right = np.inf, -np.inf
  393. for line in lines:
  394. x = line.get_xdata(orig=False)
  395. left = min(np.nanmin(x), left)
  396. right = max(np.nanmax(x), right)
  397. return left, right