_doctools.py 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  1. from __future__ import annotations
  2. from typing import TYPE_CHECKING
  3. import numpy as np
  4. import pandas as pd
  5. if TYPE_CHECKING:
  6. from collections.abc import Iterable
  7. class TablePlotter:
  8. """
  9. Layout some DataFrames in vertical/horizontal layout for explanation.
  10. Used in merging.rst
  11. """
  12. def __init__(
  13. self,
  14. cell_width: float = 0.37,
  15. cell_height: float = 0.25,
  16. font_size: float = 7.5,
  17. ) -> None:
  18. self.cell_width = cell_width
  19. self.cell_height = cell_height
  20. self.font_size = font_size
  21. def _shape(self, df: pd.DataFrame) -> tuple[int, int]:
  22. """
  23. Calculate table shape considering index levels.
  24. """
  25. row, col = df.shape
  26. return row + df.columns.nlevels, col + df.index.nlevels
  27. def _get_cells(self, left, right, vertical) -> tuple[int, int]:
  28. """
  29. Calculate appropriate figure size based on left and right data.
  30. """
  31. if vertical:
  32. # calculate required number of cells
  33. vcells = max(sum(self._shape(df)[0] for df in left), self._shape(right)[0])
  34. hcells = max(self._shape(df)[1] for df in left) + self._shape(right)[1]
  35. else:
  36. vcells = max([self._shape(df)[0] for df in left] + [self._shape(right)[0]])
  37. hcells = sum([self._shape(df)[1] for df in left] + [self._shape(right)[1]])
  38. return hcells, vcells
  39. def plot(self, left, right, labels: Iterable[str] = (), vertical: bool = True):
  40. """
  41. Plot left / right DataFrames in specified layout.
  42. Parameters
  43. ----------
  44. left : list of DataFrames before operation is applied
  45. right : DataFrame of operation result
  46. labels : list of str to be drawn as titles of left DataFrames
  47. vertical : bool, default True
  48. If True, use vertical layout. If False, use horizontal layout.
  49. """
  50. from matplotlib import gridspec
  51. import matplotlib.pyplot as plt
  52. if not isinstance(left, list):
  53. left = [left]
  54. left = [self._conv(df) for df in left]
  55. right = self._conv(right)
  56. hcells, vcells = self._get_cells(left, right, vertical)
  57. if vertical:
  58. figsize = self.cell_width * hcells, self.cell_height * vcells
  59. else:
  60. # include margin for titles
  61. figsize = self.cell_width * hcells, self.cell_height * vcells
  62. fig = plt.figure(figsize=figsize)
  63. if vertical:
  64. gs = gridspec.GridSpec(len(left), hcells)
  65. # left
  66. max_left_cols = max(self._shape(df)[1] for df in left)
  67. max_left_rows = max(self._shape(df)[0] for df in left)
  68. for i, (_left, _label) in enumerate(zip(left, labels)):
  69. ax = fig.add_subplot(gs[i, 0:max_left_cols])
  70. self._make_table(ax, _left, title=_label, height=1.0 / max_left_rows)
  71. # right
  72. ax = plt.subplot(gs[:, max_left_cols:])
  73. self._make_table(ax, right, title="Result", height=1.05 / vcells)
  74. fig.subplots_adjust(top=0.9, bottom=0.05, left=0.05, right=0.95)
  75. else:
  76. max_rows = max(self._shape(df)[0] for df in left + [right])
  77. height = 1.0 / np.max(max_rows)
  78. gs = gridspec.GridSpec(1, hcells)
  79. # left
  80. i = 0
  81. for df, _label in zip(left, labels):
  82. sp = self._shape(df)
  83. ax = fig.add_subplot(gs[0, i : i + sp[1]])
  84. self._make_table(ax, df, title=_label, height=height)
  85. i += sp[1]
  86. # right
  87. ax = plt.subplot(gs[0, i:])
  88. self._make_table(ax, right, title="Result", height=height)
  89. fig.subplots_adjust(top=0.85, bottom=0.05, left=0.05, right=0.95)
  90. return fig
  91. def _conv(self, data):
  92. """
  93. Convert each input to appropriate for table outplot.
  94. """
  95. if isinstance(data, pd.Series):
  96. if data.name is None:
  97. data = data.to_frame(name="")
  98. else:
  99. data = data.to_frame()
  100. data = data.fillna("NaN")
  101. return data
  102. def _insert_index(self, data):
  103. # insert is destructive
  104. data = data.copy()
  105. idx_nlevels = data.index.nlevels
  106. if idx_nlevels == 1:
  107. data.insert(0, "Index", data.index)
  108. else:
  109. for i in range(idx_nlevels):
  110. data.insert(i, f"Index{i}", data.index._get_level_values(i))
  111. col_nlevels = data.columns.nlevels
  112. if col_nlevels > 1:
  113. col = data.columns._get_level_values(0)
  114. values = [
  115. data.columns._get_level_values(i)._values for i in range(1, col_nlevels)
  116. ]
  117. col_df = pd.DataFrame(values)
  118. data.columns = col_df.columns
  119. data = pd.concat([col_df, data])
  120. data.columns = col
  121. return data
  122. def _make_table(self, ax, df, title: str, height: float | None = None) -> None:
  123. if df is None:
  124. ax.set_visible(False)
  125. return
  126. from pandas import plotting
  127. idx_nlevels = df.index.nlevels
  128. col_nlevels = df.columns.nlevels
  129. # must be convert here to get index levels for colorization
  130. df = self._insert_index(df)
  131. tb = plotting.table(ax, df, loc=9)
  132. tb.set_fontsize(self.font_size)
  133. if height is None:
  134. height = 1.0 / (len(df) + 1)
  135. props = tb.properties()
  136. for (r, c), cell in props["celld"].items():
  137. if c == -1:
  138. cell.set_visible(False)
  139. elif r < col_nlevels and c < idx_nlevels:
  140. cell.set_visible(False)
  141. elif r < col_nlevels or c < idx_nlevels:
  142. cell.set_facecolor("#AAAAAA")
  143. cell.set_height(height)
  144. ax.set_title(title, size=self.font_size)
  145. ax.axis("off")
  146. def main() -> None:
  147. import matplotlib.pyplot as plt
  148. p = TablePlotter()
  149. df1 = pd.DataFrame({"A": [10, 11, 12], "B": [20, 21, 22], "C": [30, 31, 32]})
  150. df2 = pd.DataFrame({"A": [10, 12], "C": [30, 32]})
  151. p.plot([df1, df2], pd.concat([df1, df2]), labels=["df1", "df2"], vertical=True)
  152. plt.show()
  153. df3 = pd.DataFrame({"X": [10, 12], "Z": [30, 32]})
  154. p.plot(
  155. [df1, df3], pd.concat([df1, df3], axis=1), labels=["df1", "df2"], vertical=False
  156. )
  157. plt.show()
  158. idx = pd.MultiIndex.from_tuples(
  159. [(1, "A"), (1, "B"), (1, "C"), (2, "A"), (2, "B"), (2, "C")]
  160. )
  161. column = pd.MultiIndex.from_tuples([(1, "A"), (1, "B")])
  162. df3 = pd.DataFrame({"v1": [1, 2, 3, 4, 5, 6], "v2": [5, 6, 7, 8, 9, 10]}, index=idx)
  163. df3.columns = column
  164. p.plot(df3, df3, labels=["df3"])
  165. plt.show()
  166. if __name__ == "__main__":
  167. main()