MatplotLibAPI 3.2.13__py3-none-any.whl → 3.2.15__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,83 @@
1
+ """Sunburst chart plotting utilities."""
2
+
3
+ from typing import Optional
4
+
5
+ import pandas as pd
6
+ import plotly.graph_objects as go
7
+
8
+ from .StyleTemplate import (
9
+ TREEMAP_STYLE_TEMPLATE,
10
+ StyleTemplate,
11
+ validate_dataframe,
12
+ )
13
+
14
+
15
+ def fplot_sunburst(
16
+ pd_df: pd.DataFrame,
17
+ labels: str,
18
+ parents: str,
19
+ values: str,
20
+ style: StyleTemplate = TREEMAP_STYLE_TEMPLATE,
21
+ title: Optional[str] = None,
22
+ sort_by: Optional[str] = None,
23
+ ascending: bool = False,
24
+ max_values: int = 100,
25
+ fig: Optional[go.Figure] = None,
26
+ ) -> go.Figure:
27
+ """Return a figure containing the sunburst plot.
28
+
29
+ Parameters
30
+ ----------
31
+ pd_df : pd.DataFrame
32
+ DataFrame containing the data to plot.
33
+ labels : str
34
+ Column representing the labels of the sectors.
35
+ parents : str
36
+ Column representing the parent of each sector.
37
+ values : str
38
+ Column containing values for each sunburst sector.
39
+ style : StyleTemplate, optional
40
+ Style configuration. The default is `TREEMAP_STYLE_TEMPLATE`.
41
+ title : str, optional
42
+ Plot title.
43
+ sort_by : str, optional
44
+ Column used to sort data.
45
+ ascending : bool, optional
46
+ Sort order for the data. The default is `False`.
47
+ max_values : int, optional
48
+ Maximum number of rows to plot. The default is 100.
49
+ fig : go.Figure, optional
50
+ Existing figure to add the sunburst chart to.
51
+
52
+ Returns
53
+ -------
54
+ go.Figure
55
+ Figure containing the sunburst plot.
56
+ """
57
+ cols = [labels, parents, values]
58
+ validate_dataframe(pd_df, cols=cols, sort_by=sort_by)
59
+ if not sort_by:
60
+ sort_by = values
61
+ df = pd_df.sort_values(by=sort_by, ascending=ascending)[cols].head(max_values)
62
+
63
+ trace = go.Sunburst(
64
+ labels=df[labels],
65
+ parents=df[parents],
66
+ values=df[values],
67
+ textinfo="label+percent entry",
68
+ )
69
+
70
+ if not fig:
71
+ fig = go.Figure(trace)
72
+ else:
73
+ fig.add_trace(trace)
74
+
75
+ fig.update_layout(
76
+ title=title,
77
+ plot_bgcolor=style.background_color,
78
+ paper_bgcolor=style.background_color,
79
+ font=dict(family=style.font_name, size=style.font_size, color=style.font_color),
80
+ showlegend=style.legend if style else True,
81
+ )
82
+
83
+ return fig
MatplotLibAPI/Table.py CHANGED
@@ -1,91 +1,220 @@
1
- from typing import List, Optional, Tuple
1
+ """Table plotting helpers."""
2
+
3
+ from typing import List, Optional, Tuple, cast
2
4
  import pandas as pd
3
5
  import matplotlib.pyplot as plt
4
6
  from matplotlib.axes import Axes
5
7
  from matplotlib.figure import Figure
8
+ from matplotlib.transforms import Bbox
9
+ from matplotlib.table import Table
6
10
 
7
- from MatplotLibAPI.StyleTemplate import StyleTemplate, string_formatter, validate_dataframe
11
+ from .StyleTemplate import StyleTemplate, string_formatter, validate_dataframe
8
12
 
9
13
  TABLE_STYLE_TEMPLATE = StyleTemplate(
10
- background_color='black',
11
- fig_border='darkgrey',
12
- font_color='white',
13
- palette='magma'
14
+ background_color="black", fig_border="darkgrey", font_color="white", palette="magma"
14
15
  )
15
16
 
16
17
 
17
- def aplot_table(pd_df: pd.DataFrame,
18
- cols: List[str],
19
- title: Optional[str] = None,
20
- style: StyleTemplate = TABLE_STYLE_TEMPLATE,
21
- max_values: int = 20,
22
- sort_by: Optional[str] = None,
23
- ascending: bool = False,
24
- ax: Optional[Axes] = None
25
- ) -> Axes:
18
+ def _prepare_table_data(
19
+ pd_df: pd.DataFrame,
20
+ cols: List[str],
21
+ sort_by: Optional[str],
22
+ ascending: bool,
23
+ max_values: int,
24
+ style: StyleTemplate,
25
+ ) -> pd.DataFrame:
26
+ """Prepare data for table plotting.
27
+
28
+ Parameters
29
+ ----------
30
+ pd_df : pd.DataFrame
31
+ Input DataFrame.
32
+ cols : List[str]
33
+ Columns to include in the table.
34
+ sort_by : Optional[str]
35
+ Column to sort by.
36
+ ascending : bool
37
+ Sort order.
38
+ max_values : int
39
+ Maximum number of rows to display.
40
+ style : StyleTemplate
41
+ Styling for the plot.
42
+
43
+ Returns
44
+ -------
45
+ pd.DataFrame
46
+ Prepared DataFrame for plotting.
47
+
48
+ Raises
49
+ ------
50
+ AttributeError
51
+ If required columns are missing from the DataFrame.
52
+ """
26
53
  validate_dataframe(pd_df, cols=cols, sort_by=sort_by)
27
54
 
28
- if not sort_by:
55
+ if sort_by is None:
29
56
  sort_by = cols[0]
30
57
 
31
- plot_df = pd_df[cols].sort_values(
32
- by=sort_by, ascending=ascending).head(max_values)
33
-
34
- col_labels = cols
58
+ plot_df = (
59
+ pd_df[cols]
60
+ .sort_values(by=[sort_by], ascending=ascending) # type: ignore
61
+ .head(max_values)
62
+ .copy()
63
+ )
35
64
 
36
65
  if style.format_funcs:
37
66
  for col, func in style.format_funcs.items():
38
- if col in plot_df.columns:
67
+ if col in plot_df.columns and func is not None:
39
68
  plot_df[col] = plot_df[col].apply(func)
69
+ return plot_df
70
+
71
+
72
+ def _format_table(table: Table, style: StyleTemplate):
73
+ """Format the table cells and font.
74
+
75
+ Parameters
76
+ ----------
77
+ table : matplotlib.table.Table
78
+ The table object to format.
79
+ style : StyleTemplate
80
+ The style configuration to apply.
81
+ """
82
+ table.auto_set_font_size(False)
83
+ table.set_fontsize(style.font_size)
84
+ table.scale(1.2, 1.2)
85
+
86
+ for key, cell in table.get_celld().items():
87
+ cell.set_fontsize(style.font_size)
88
+ cell.set_facecolor(style.background_color)
89
+ cell.get_text().set_color(style.font_color)
90
+
40
91
 
41
- def format_table(table):
42
- table.auto_set_font_size(False)
43
- table.set_fontsize(style.font_size)
44
- table.scale(1.2, 1.2)
92
+ def aplot_table(
93
+ pd_df: pd.DataFrame,
94
+ cols: List[str],
95
+ title: Optional[str] = None,
96
+ style: StyleTemplate = TABLE_STYLE_TEMPLATE,
97
+ max_values: int = 20,
98
+ sort_by: Optional[str] = None,
99
+ ascending: bool = False,
100
+ ax: Optional[Axes] = None,
101
+ ) -> Axes:
102
+ """Render a table into the provided axes.
45
103
 
46
- for key, cell in table.get_celld().items():
47
- cell.set_fontsize(style.font_size)
48
- cell.set_facecolor(style.background_color)
49
- cell.get_text().set_color(style.font_color)
104
+ Parameters
105
+ ----------
106
+ pd_df : pandas.DataFrame
107
+ DataFrame containing the data to display.
108
+ cols : list of str
109
+ Columns to include in the table.
110
+ title : str, optional
111
+ Table title, by default ``None``.
112
+ style : StyleTemplate, optional
113
+ Style configuration, by default ``TABLE_STYLE_TEMPLATE``.
114
+ max_values : int, optional
115
+ Maximum number of rows to display, by default ``20``.
116
+ sort_by : str, optional
117
+ Column used for sorting, by default ``None``.
118
+ ascending : bool, optional
119
+ Sort order for the data, by default ``False``.
120
+ ax : matplotlib.axes.Axes, optional
121
+ Axes to draw on, by default ``None``.
50
122
 
123
+ Returns
124
+ -------
125
+ matplotlib.axes.Axes
126
+ Matplotlib axes containing the rendered table.
127
+
128
+ Raises
129
+ ------
130
+ AttributeError
131
+ If required columns are not in the DataFrame.
132
+
133
+ Examples
134
+ --------
135
+ >>> import pandas as pd
136
+ >>> import matplotlib.pyplot as plt
137
+ >>> from MatplotLibAPI.Table import aplot_table
138
+ >>> data = {'col1': [1, 2], 'col2': [3, 4]}
139
+ >>> df = pd.DataFrame(data)
140
+ >>> fig, ax = plt.subplots()
141
+ >>> aplot_table(df, cols=['col1', 'col2'], ax=ax)
142
+ """
51
143
  if ax is None:
52
- ax = plt.gca()
144
+ ax = cast(Axes, plt.gca())
145
+
146
+ plot_df = _prepare_table_data(pd_df, cols, sort_by, ascending, max_values, style)
53
147
 
54
148
  table_plot = ax.table(
55
- cellText=plot_df.values,
56
- colLabels=[string_formatter(colLabel) for colLabel in col_labels],
57
- cellLoc='center',
149
+ cellText=plot_df.values.tolist(),
150
+ colLabels=[string_formatter(colLabel) for colLabel in cols],
151
+ cellLoc="center",
58
152
  colWidths=style.col_widths,
59
- bbox=[0, -0.3, 1, 1.3])
60
- format_table(table_plot)
153
+ bbox=Bbox.from_bounds(0, -0.3, 1, 1.3),
154
+ )
155
+
156
+ _format_table(table_plot, style)
157
+
61
158
  ax.set_facecolor(style.background_color)
62
159
  ax.set_axis_off()
63
160
  ax.grid(False)
64
161
  if title:
65
- ax.set_title(title, color=style.font_color, fontsize=style.font_size*2)
66
- ax.title.set_position([0.5, 1.05])
162
+ ax.set_title(title, color=style.font_color, fontsize=style.font_size * 2)
163
+ ax.title.set_position((0.5, 1.05))
67
164
  return ax
68
165
 
69
166
 
70
- def fplot_table(pd_df: pd.DataFrame,
71
- cols: List[str],
72
- title: Optional[str] = None,
73
- style: StyleTemplate = TABLE_STYLE_TEMPLATE,
74
- max_values: int = 20,
75
- sort_by: Optional[str] = None,
76
- ascending: bool = False,
77
- figsize: Tuple[float, float] = (19.2, 10.8)
78
- ) -> Figure:
79
- fig = plt.figure(figsize=figsize)
167
+ def fplot_table(
168
+ pd_df: pd.DataFrame,
169
+ cols: List[str],
170
+ title: Optional[str] = None,
171
+ style: StyleTemplate = TABLE_STYLE_TEMPLATE,
172
+ max_values: int = 20,
173
+ sort_by: Optional[str] = None,
174
+ ascending: bool = False,
175
+ figsize: Tuple[float, float] = (19.2, 10.8),
176
+ ) -> Figure:
177
+ """Return a new figure containing a formatted table.
178
+
179
+ Parameters
180
+ ----------
181
+ pd_df : pandas.DataFrame
182
+ DataFrame containing the data to display.
183
+ cols : list of str
184
+ Columns to include in the table.
185
+ title : str, optional
186
+ Table title, by default ``None``.
187
+ style : StyleTemplate, optional
188
+ Style configuration, by default ``TABLE_STYLE_TEMPLATE``.
189
+ max_values : int, optional
190
+ Maximum number of rows to display, by default ``20``.
191
+ sort_by : str, optional
192
+ Column used for sorting, by default ``None``.
193
+ ascending : bool, optional
194
+ Sort order for the data, by default ``False``.
195
+ figsize : tuple of float, optional
196
+ Size of the created figure, by default ``(19.2, 10.8)``.
197
+
198
+ Returns
199
+ -------
200
+ matplotlib.figure.Figure
201
+ Matplotlib figure containing the table.
202
+
203
+ Raises
204
+ ------
205
+ AttributeError
206
+ If required columns are not in the DataFrame.
207
+
208
+ Examples
209
+ --------
210
+ >>> import pandas as pd
211
+ >>> from MatplotLibAPI.Table import fplot_table
212
+ >>> data = {'col1': [1, 2], 'col2': [3, 4]}
213
+ >>> df = pd.DataFrame(data)
214
+ >>> fig = fplot_table(df, cols=['col1', 'col2'])
215
+ """
216
+ fig = cast(Figure, plt.figure(figsize=figsize))
80
217
  fig.patch.set_facecolor(style.background_color)
81
218
  ax = fig.add_subplot()
82
- ax = aplot_table(pd_df,
83
- cols,
84
- title,
85
- style,
86
- max_values,
87
- sort_by,
88
- ascending,
89
- ax
90
- )
219
+ ax = aplot_table(pd_df, cols, title, style, max_values, sort_by, ascending, ax)
91
220
  return fig