acadplot 0.1.2__py3-none-any.whl → 0.2.0__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.
acadplot/__init__.py CHANGED
@@ -31,7 +31,7 @@ from .utils import (
31
31
  theme_preview,
32
32
  )
33
33
 
34
- __version__ = "0.1.2"
34
+ __version__ = "0.2.0"
35
35
  __all__ = [
36
36
  "plot_line",
37
37
  "plot_bar",
acadplot/bar.py CHANGED
@@ -1,47 +1,8 @@
1
1
  from typing import List, Optional, Sequence, Tuple
2
2
 
3
- import matplotlib.pyplot as plt
4
- from matplotlib.colors import to_rgba
5
-
6
- from .draw import draw_bar, resolve_color_key, resolve_pattern_key
7
- from .styles import (
8
- apply_axis_style,
9
- apply_grid,
10
- configure_plot_style,
11
- get_current_style,
12
- )
13
- from .utils import new_alpha, save, styled_legend
14
-
15
-
16
- def _prepare_axes(ax, fig_size):
17
- if ax is None:
18
- return plt.subplots(figsize=fig_size)
19
- return ax.figure, ax
20
-
21
-
22
- def _resolve_text_sizes(style, font_size, label_size, tick_size, legend_size):
23
- font_size_override = font_size
24
- if font_size is None:
25
- font_size = float(style["font_size"])
26
- if label_size is None:
27
- label_size = (
28
- font_size_override
29
- if font_size_override is not None
30
- else float(style["label_size"])
31
- )
32
- if tick_size is None:
33
- tick_size = (
34
- font_size_override
35
- if font_size_override is not None
36
- else float(style["tick_size"])
37
- )
38
- if legend_size is None:
39
- legend_size = (
40
- font_size_override
41
- if font_size_override is not None
42
- else float(style["legend_size"])
43
- )
44
- return font_size, label_size, tick_size, legend_size
3
+ from .draw import draw_bar, resolve_pattern_key, series_defaults, start_plot
4
+ from .styles import apply_axis_style, apply_grid
5
+ from .utils import save, styled_legend
45
6
 
46
7
 
47
8
  def _apply_bar_axis_style(ax, tick_size: float) -> None:
@@ -52,80 +13,53 @@ def _apply_bar_axis_style(ax, tick_size: float) -> None:
52
13
 
53
14
  def _parse_bar(bar):
54
15
  if len(bar) == 5:
55
- x, y, color_key, pattern_key, bar_label = bar
56
- return x, y, color_key, pattern_key, bar_label
57
- if len(bar) == 4:
58
- x, y, color_key, bar_label = bar
59
- return x, y, color_key, None, bar_label
60
- if len(bar) == 3:
61
- x, y, bar_label = bar
62
- return x, y, None, None, bar_label
63
- raise ValueError("Bar entries must be (x, y, color, label) or (x, y, label).")
64
-
65
-
66
- def _parse_group_bar(entry):
67
- if len(entry) == 4:
68
- value, color_key, pattern_key, bar_label = entry
69
- return value, color_key, pattern_key, bar_label
70
- if len(entry) == 3:
71
- value, color_key, bar_label = entry
72
- return value, color_key, None, bar_label
73
- if len(entry) == 2:
74
- value, bar_label = entry
75
- return value, None, None, bar_label
76
- raise ValueError(
77
- "Grouped bar entries must be (value, color, label) or (value, label)."
78
- )
79
-
80
-
81
- def _parse_stack(stack):
82
- if len(stack) == 4:
83
- values, color_key, pattern_key, stack_label = stack
84
- return values, color_key, pattern_key, stack_label
85
- if len(stack) == 3:
86
- values, color_key, stack_label = stack
87
- return values, color_key, None, stack_label
88
- if len(stack) == 2:
89
- values, stack_label = stack
90
- return values, None, None, stack_label
91
- raise ValueError("Stack entries must be (values, color, label) or (values, label).")
16
+ x, y, color_key, pattern_key, label = bar
17
+ elif len(bar) == 4:
18
+ x, y, color_key, label = bar
19
+ pattern_key = None
20
+ elif len(bar) == 3:
21
+ x, y, label = bar
22
+ color_key = pattern_key = None
23
+ else:
24
+ raise ValueError("Bar entries must be (x, y, color, label) or (x, y, label).")
25
+ return x, y, series_defaults(label, color_key)[0], pattern_key, label
26
+
27
+
28
+ def _parse_series(series):
29
+ if len(series) == 4:
30
+ values, color_key, pattern_key, label = series
31
+ elif len(series) == 3:
32
+ values, color_key, label = series
33
+ pattern_key = None
34
+ elif len(series) == 2:
35
+ values, label = series
36
+ color_key = pattern_key = None
37
+ else:
38
+ raise ValueError(
39
+ "Series entries must be (values, label), (values, color, label), "
40
+ "or (values, color, pattern, label)."
41
+ )
42
+ return values, series_defaults(label, color_key)[0], pattern_key, label
92
43
 
93
44
 
94
45
  def _resolve_pattern(patterns, index: int, label: str, explicit_pattern):
95
- if explicit_pattern is not None:
96
- return resolve_pattern_key(explicit_pattern)
97
- if patterns is None:
98
- return None
99
- if isinstance(patterns, dict):
100
- return resolve_pattern_key(patterns.get(label))
101
- if not patterns:
102
- return None
103
- return resolve_pattern_key(patterns[index % len(patterns)])
104
-
105
-
106
- def _add_legend(
107
- ax,
108
- location: str,
109
- legend_size: float,
110
- ncols: int,
111
- columnspacing: float,
112
- legend_outside: bool | str,
113
- ):
114
- return styled_legend(
115
- ax,
116
- location,
117
- legend_size=legend_size,
118
- ncols=ncols,
119
- columnspacing=columnspacing,
120
- legend_outside=legend_outside,
121
- )
46
+ """Tuple pattern, else the per-call ``patterns``, else ``series_styles``."""
47
+ pattern = explicit_pattern
48
+ if pattern is None and patterns:
49
+ if isinstance(patterns, dict):
50
+ pattern = patterns.get(label)
51
+ else:
52
+ pattern = patterns[index % len(patterns)]
53
+ if pattern is None:
54
+ pattern = series_defaults(label)[2]
55
+ return resolve_pattern_key(pattern)
122
56
 
123
57
 
124
58
  def plot_bar(
125
59
  bars: List[Tuple],
126
- location: str,
60
+ location: Optional[str] = "best",
127
61
  fig_size: Optional[Tuple[float, float]] = None,
128
- label: Tuple[str, str] = ("x-label", "y-label"),
62
+ label: Optional[Tuple[str, str]] = None,
129
63
  ax=None,
130
64
  xticklabels: Optional[List[str]] = None,
131
65
  rotation: float = 0.0,
@@ -138,7 +72,7 @@ def plot_bar(
138
72
  bar_width: float = 0.35,
139
73
  patterns: Optional[Sequence[str | int] | dict[str, str | int]] = None,
140
74
  grid: Optional[str] = None,
141
- fname: Optional[str] = "bar_plot.pdf",
75
+ fname: Optional[str] = None,
142
76
  legend_outside: bool | str = False,
143
77
  ):
144
78
  """Plot a bar chart with a legend.
@@ -146,10 +80,11 @@ def plot_bar(
146
80
  Args:
147
81
  bars (List[Tuple]): List of bars, each defined by x positions, y values,
148
82
  optional color name/index/raw Matplotlib color, and label. Omit color
149
- to use the active theme palette cycle.
150
- location (str): Location of the legend.
83
+ to use the active theme palette cycle. Series that share x positions
84
+ are drawn side by side, centered on each position.
85
+ location (str, optional): Legend location, or None for no legend. Defaults to "best".
151
86
  fig_size (Tuple[float, float], optional): Figure size. Defaults to the active style.
152
- label (Tuple[str, str], optional): Labels for the x and y axes. Defaults to ("x-label", "y-label").
87
+ label (Tuple[str, str], optional): Labels for the x and y axes. Defaults to None (no axis labels).
153
88
  ax (Optional[plt.Axes], optional): Axes to plot on. Creates new if None. Defaults to None.
154
89
  xticklabels (Optional[List[str]], optional): Labels for x-axis ticks. Defaults to None.
155
90
  rotation (float, optional): Rotation angle for x-tick labels. Defaults to 0.0.
@@ -161,32 +96,31 @@ def plot_bar(
161
96
  columnspacing (float, optional): Spacing between legend columns. Defaults to 0.5.
162
97
  bar_width (float, optional): Width of the bars. Defaults to 0.35.
163
98
  grid (str, optional): Grid preset: "major-y", "major", "major-minor", or "none".
164
- fname (Optional[str], optional): Filename to save the plot. Defaults to "bar_plot.pdf".
99
+ fname (Optional[str], optional): Filename to save the plot. Defaults to None (not saved).
165
100
  """
166
- style = get_current_style()
167
- if fig_size is None:
168
- fig_size = style["fig_size"]
169
- font_size, label_size, tick_size, legend_size = _resolve_text_sizes(
170
- style,
171
- font_size,
172
- label_size,
173
- tick_size,
174
- legend_size,
101
+ fig, ax, style, tick_size, legend_size = start_plot(
102
+ ax, fig_size, label, font_size, label_size, tick_size, legend_size
175
103
  )
176
-
177
- fig, ax = _prepare_axes(ax, fig_size)
178
-
179
- ax.set_prop_cycle(color=list(style["palette"]))
180
- ax.set_xlabel(label[0], fontsize=label_size)
181
- ax.set_ylabel(label[1], fontsize=label_size)
182
104
  apply_grid(ax, grid or str(style["bar_grid"]))
183
105
 
106
+ all_x = [pos for bar in bars for pos in bar[0]]
107
+ dodge = len(all_x) != len(set(all_x))
184
108
  for bar_idx, bar in enumerate(bars):
185
109
  x, y, color_key, pattern_key, bar_label = _parse_bar(bar)
110
+ if dodge:
111
+ offset = (bar_idx - len(bars) / 2 + 0.5) * bar_width
112
+ x = [pos + offset for pos in x]
186
113
  pattern = _resolve_pattern(patterns, bar_idx, bar_label, pattern_key)
187
114
  draw_bar(ax, x, y, color_key, bar_label, bar_width, pattern)
188
115
 
189
- _add_legend(ax, location, legend_size, ncols, columnspacing, legend_outside)
116
+ styled_legend(
117
+ ax,
118
+ location,
119
+ legend_size=legend_size,
120
+ ncols=ncols,
121
+ columnspacing=columnspacing,
122
+ legend_outside=legend_outside,
123
+ )
190
124
 
191
125
  if xticklabels is not None and bars:
192
126
  ax.set_xticks(bars[0][0])
@@ -201,10 +135,11 @@ def plot_bar(
201
135
 
202
136
 
203
137
  def plot_grouped_bar(
204
- groups: List[Tuple[str, List[Tuple]]],
205
- location: str,
138
+ categories: List[str],
139
+ series: List[Tuple],
140
+ location: Optional[str] = "best",
206
141
  fig_size: Optional[Tuple[float, float]] = None,
207
- label: Tuple[str, str] = ("x-label", "y-label"),
142
+ label: Optional[Tuple[str, str]] = None,
208
143
  ax=None,
209
144
  rotation: float = 0.0,
210
145
  font_size: Optional[float] = None,
@@ -216,18 +151,19 @@ def plot_grouped_bar(
216
151
  bar_width: float = 0.25,
217
152
  patterns: Optional[Sequence[str | int] | dict[str, str | int]] = None,
218
153
  grid: Optional[str] = None,
219
- fname: Optional[str] = "grouped_bar_plot.pdf",
154
+ fname: Optional[str] = None,
220
155
  legend_outside: bool | str = False,
221
156
  ):
222
- """Plot a grouped bar chart with multiple bars per group.
157
+ """Plot a grouped bar chart: one bar per series inside each category.
223
158
 
224
159
  Args:
225
- groups (List[Tuple[str, List[Tuple]]]): List of groups, each defined by
226
- group name and a list of (value, optional color, label) tuples. Omit
227
- color to use the active theme palette cycle.
228
- location (str): Location of the legend.
160
+ categories (List[str]): Category labels for the x-axis.
161
+ series (List[Tuple]): One entry per bar in each group: (values, label),
162
+ (values, color, label), or (values, color, pattern, label), with one
163
+ value per category. Omit color to use the active theme palette cycle.
164
+ location (str, optional): Legend location, or None for no legend. Defaults to "best".
229
165
  fig_size (Tuple[float, float], optional): Figure size. Defaults to the active style.
230
- label (Tuple[str, str], optional): Labels for the x and y axes. Defaults to ("x-label", "y-label").
166
+ label (Tuple[str, str], optional): Labels for the x and y axes. Defaults to None (no axis labels).
231
167
  ax (Optional[plt.Axes], optional): Axes to plot on. Creates new if None. Defaults to None.
232
168
  rotation (float, optional): Rotation angle for x-tick labels. Defaults to 0.0.
233
169
  font_size (float, optional): Base font size for labels, ticks, and legend. Defaults to the active style.
@@ -238,42 +174,37 @@ def plot_grouped_bar(
238
174
  columnspacing (float, optional): Spacing between legend columns. Defaults to 0.5.
239
175
  bar_width (float, optional): Width of each bar. Defaults to 0.25.
240
176
  grid (str, optional): Grid preset: "major-y", "major", "major-minor", or "none".
241
- fname (Optional[str], optional): Filename to save the plot. Defaults to "grouped_bar_plot.pdf".
177
+ fname (Optional[str], optional): Filename to save the plot. Defaults to None (not saved).
242
178
  """
243
- style = get_current_style()
244
- if fig_size is None:
245
- fig_size = style["fig_size"]
246
- font_size, label_size, tick_size, legend_size = _resolve_text_sizes(
247
- style,
248
- font_size,
249
- label_size,
250
- tick_size,
251
- legend_size,
179
+ if isinstance(series, str):
180
+ raise TypeError(
181
+ "plot_grouped_bar takes (categories, series, location); pass series "
182
+ "as [(values, label), ...] with one value per category."
183
+ )
184
+ fig, ax, style, tick_size, legend_size = start_plot(
185
+ ax, fig_size, label, font_size, label_size, tick_size, legend_size
252
186
  )
253
-
254
- fig, ax = _prepare_axes(ax, fig_size)
255
-
256
- ax.set_prop_cycle(color=list(style["palette"]))
257
- ax.set_xlabel(label[0], fontsize=label_size)
258
- ax.set_ylabel(label[1], fontsize=label_size)
259
187
  apply_grid(ax, grid or str(style["bar_grid"]))
260
188
 
261
- n_bars = len(groups[0][1]) if groups else 0
262
- group_positions = range(len(groups))
263
-
264
- for bar_idx in range(n_bars):
265
- positions = [
266
- pos + (bar_idx - n_bars / 2 + 0.5) * bar_width for pos in group_positions
267
- ]
268
- values = [group[1][bar_idx][0] for group in groups]
269
- _, color_key, pattern_key, bar_label = _parse_group_bar(groups[0][1][bar_idx])
270
- pattern = _resolve_pattern(patterns, bar_idx, bar_label, pattern_key)
189
+ group_positions = range(len(categories))
190
+ for idx, entry in enumerate(series):
191
+ values, color_key, pattern_key, bar_label = _parse_series(entry)
192
+ offset = (idx - len(series) / 2 + 0.5) * bar_width
193
+ positions = [pos + offset for pos in group_positions]
194
+ pattern = _resolve_pattern(patterns, idx, bar_label, pattern_key)
271
195
  draw_bar(ax, positions, values, color_key, bar_label, bar_width, pattern)
272
196
 
273
197
  ax.set_xticks(list(group_positions))
274
- ax.set_xticklabels([g[0] for g in groups], rotation=rotation, fontsize=tick_size)
198
+ ax.set_xticklabels(categories, rotation=rotation, fontsize=tick_size)
275
199
 
276
- _add_legend(ax, location, legend_size, ncols, columnspacing, legend_outside)
200
+ styled_legend(
201
+ ax,
202
+ location,
203
+ legend_size=legend_size,
204
+ ncols=ncols,
205
+ columnspacing=columnspacing,
206
+ legend_outside=legend_outside,
207
+ )
277
208
  _apply_bar_axis_style(ax, tick_size)
278
209
 
279
210
  if fname:
@@ -285,9 +216,9 @@ def plot_grouped_bar(
285
216
  def plot_stacked_bar(
286
217
  categories: List[str],
287
218
  stacks: List[Tuple],
288
- location: str,
219
+ location: Optional[str] = "best",
289
220
  fig_size: Optional[Tuple[float, float]] = None,
290
- label: Tuple[str, str] = ("x-label", "y-label"),
221
+ label: Optional[Tuple[str, str]] = None,
291
222
  ax=None,
292
223
  rotation: float = 0.0,
293
224
  font_size: Optional[float] = None,
@@ -299,19 +230,19 @@ def plot_stacked_bar(
299
230
  bar_width: float = 0.35,
300
231
  patterns: Optional[Sequence[str | int] | dict[str, str | int]] = None,
301
232
  grid: Optional[str] = None,
302
- fname: Optional[str] = "stacked_bar_plot.pdf",
233
+ fname: Optional[str] = None,
303
234
  legend_outside: bool | str = False,
304
235
  ):
305
236
  """Plot a stacked bar chart.
306
237
 
307
238
  Args:
308
239
  categories (List[str]): Category labels for the x-axis.
309
- stacks (List[Tuple]): List of stacks, each defined by values, optional
310
- color name/index/raw Matplotlib color, and label. Omit color to use
311
- the active theme palette cycle.
312
- location (str): Location of the legend.
240
+ stacks (List[Tuple]): One entry per stack layer: (values, label),
241
+ (values, color, label), or (values, color, pattern, label), with one
242
+ value per category. Omit color to use the active theme palette cycle.
243
+ location (str, optional): Legend location, or None for no legend. Defaults to "best".
313
244
  fig_size (Tuple[float, float], optional): Figure size. Defaults to the active style.
314
- label (Tuple[str, str], optional): Labels for the x and y axes. Defaults to ("x-label", "y-label").
245
+ label (Tuple[str, str], optional): Labels for the x and y axes. Defaults to None (no axis labels).
315
246
  ax (Optional[plt.Axes], optional): Axes to plot on. Creates new if None. Defaults to None.
316
247
  rotation (float, optional): Rotation angle for x-tick labels. Defaults to 0.0.
317
248
  font_size (float, optional): Base font size for labels, ticks, and legend. Defaults to the active style.
@@ -322,107 +253,44 @@ def plot_stacked_bar(
322
253
  columnspacing (float, optional): Spacing between legend columns. Defaults to 0.5.
323
254
  bar_width (float, optional): Width of the bars. Defaults to 0.35.
324
255
  grid (str, optional): Grid preset: "major-y", "major", "major-minor", or "none".
325
- fname (Optional[str], optional): Filename to save the plot. Defaults to "stacked_bar_plot.pdf".
256
+ fname (Optional[str], optional): Filename to save the plot. Defaults to None (not saved).
326
257
  """
327
- style = get_current_style()
328
- if fig_size is None:
329
- fig_size = style["fig_size"]
330
- font_size, label_size, tick_size, legend_size = _resolve_text_sizes(
331
- style,
332
- font_size,
333
- label_size,
334
- tick_size,
335
- legend_size,
258
+ fig, ax, style, tick_size, legend_size = start_plot(
259
+ ax, fig_size, label, font_size, label_size, tick_size, legend_size
336
260
  )
337
-
338
- fig, ax = _prepare_axes(ax, fig_size)
339
-
340
- ax.set_prop_cycle(color=list(style["palette"]))
341
- ax.set_xlabel(label[0], fontsize=label_size)
342
- ax.set_ylabel(label[1], fontsize=label_size)
343
261
  apply_grid(ax, grid or str(style["bar_grid"]))
344
262
 
345
263
  x_positions = range(len(categories))
346
264
  bottoms = [0.0] * len(categories)
347
-
348
- for stack_idx, stack in enumerate(stacks):
349
- values, color_key, pattern_key, stack_label = _parse_stack(stack)
350
- color = resolve_color_key(color_key)
351
- pattern = _resolve_pattern(patterns, stack_idx, stack_label, pattern_key)
352
- bar_alpha = float(style["bar_alpha"])
353
- bar_edge_color = str(style["bar_edge_color"])
354
- color_kwargs = {"edgecolor": bar_edge_color}
355
- if color is not None:
356
- color_kwargs["facecolor"] = new_alpha(to_rgba(color), bar_alpha)
357
- container = ax.bar(
265
+ for idx, stack in enumerate(stacks):
266
+ values, color_key, pattern_key, stack_label = _parse_series(stack)
267
+ pattern = _resolve_pattern(patterns, idx, stack_label, pattern_key)
268
+ draw_bar(
269
+ ax,
358
270
  x_positions,
359
271
  values,
272
+ color_key,
273
+ stack_label,
360
274
  bar_width,
275
+ pattern,
361
276
  bottom=bottoms,
362
- linewidth=float(style["bar_edge_width"]),
363
- hatch=pattern,
364
- label=stack_label,
365
- zorder=3,
366
- **color_kwargs,
367
277
  )
368
- for patch in container.patches:
369
- if color is None:
370
- patch.set_facecolor(
371
- new_alpha(to_rgba(patch.get_facecolor()), bar_alpha)
372
- )
373
- patch.set_edgecolor(bar_edge_color)
374
- patch.set_alpha(None)
375
278
  bottoms = [bottom + value for bottom, value in zip(bottoms, values)]
376
279
 
377
280
  ax.set_xticks(list(x_positions))
378
281
  ax.set_xticklabels(categories, rotation=rotation, fontsize=tick_size)
379
282
 
380
- _add_legend(ax, location, legend_size, ncols, columnspacing, legend_outside)
283
+ styled_legend(
284
+ ax,
285
+ location,
286
+ legend_size=legend_size,
287
+ ncols=ncols,
288
+ columnspacing=columnspacing,
289
+ legend_outside=legend_outside,
290
+ )
381
291
  _apply_bar_axis_style(ax, tick_size)
382
292
 
383
293
  if fname:
384
294
  save(fig, fname, close=False)
385
295
 
386
296
  return fig, ax
387
-
388
-
389
- if __name__ == "__main__":
390
- configure_plot_style()
391
-
392
- bar_data: List[Tuple[List[float], List[float], str | int, str]] = [
393
- ([0, 1, 2, 3], [10, 20, 15, 25], "blue", "Bar A"),
394
- ([0, 1, 2, 3], [8, 15, 12, 20], "orange", "Bar B"),
395
- ]
396
- plot_bar(
397
- bar_data,
398
- "upper left",
399
- xticklabels=["A", "B", "C", "D"],
400
- fname="examples/bar_plot.png",
401
- font_size=8,
402
- )
403
-
404
- grouped_data: List[Tuple[str, List[Tuple[float, str | int, str]]]] = [
405
- ("Model X", [(10, "blue", "Train"), (8, "orange", "Val")]),
406
- ("Model Y", [(15, "blue", "Train"), (12, "orange", "Val")]),
407
- ("Model Z", [(12, "blue", "Train"), (14, "orange", "Val")]),
408
- ]
409
- plot_grouped_bar(
410
- grouped_data,
411
- "upper left",
412
- fname="examples/grouped_bar_plot.png",
413
- font_size=8,
414
- )
415
-
416
- categories = ["Dataset A", "Dataset B", "Dataset C"]
417
- stacked_data: List[Tuple[List[float], str | int, str]] = [
418
- ([10, 20, 15], "blue", "Method A"),
419
- ([5, 10, 8], "orange", "Method B"),
420
- ([3, 5, 4], "green", "Method C"),
421
- ]
422
- plot_stacked_bar(
423
- categories,
424
- stacked_data,
425
- "upper left",
426
- fname="examples/stacked_bar_plot.png",
427
- font_size=8,
428
- )