_doctools.py 6.5 KB

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