-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbar.py
More file actions
309 lines (277 loc) · 9.18 KB
/
Copy pathbar.py
File metadata and controls
309 lines (277 loc) · 9.18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
"""Bar chart variants: simple, grouped, and stacked.
Three functions are provided:
* ``bar_plot`` — single-series bar chart with optional value labels.
* ``grouped_bar_plot`` — side-by-side grouped bars for multi-series comparison.
* ``stacked_bar_plot`` — stacked bars for part-to-whole composition.
Example
-------
>>> import numpy as np
>>> from academic_plot import bar_plot, savefig
>>> fig = bar_plot(
... np.array([85, 92, 78]),
... ["Method A", "Method B", "Method C"],
... ylabel="Accuracy (%)",
... )
>>> savefig(fig, "bar_demo")
"""
from __future__ import annotations
from typing import Sequence
import matplotlib.pyplot as plt
import numpy as np
from .style import PALETTE, FIGSIZES, GRID_ALPHA, GRID_LINEWIDTH, GRID_COLOR, Z_ORDER, savefig, apply_grid
from .utils import validate_arrays
def bar_plot(
values: np.ndarray,
labels: Sequence[str],
*,
xlabel: str | None = None,
ylabel: str = "Value",
title: str | None = None,
color: str | None = None,
bar_width: float = 0.55,
bar_edgecolor: str = "white",
bar_edgewidth: float = 0.5,
show_values: bool = True,
value_fontsize: float = 6,
value_fmt: str = ".2f",
value_color: str = "#333",
show_grid: bool = True,
grid_alpha: float = GRID_ALPHA,
grid_linewidth: float = GRID_LINEWIDTH,
grid_color: str = GRID_COLOR,
xtick_rotation: float = 0,
figsize: tuple[float, float] = FIGSIZES["single"],
) -> plt.Figure:
"""Simple bar chart with optional value annotations above each bar.
Parameters
----------
values : np.ndarray
Bar heights.
labels : sequence of str
Category labels on the x-axis.
xlabel : str or None
x-axis label. Often omitted for categorical bar charts.
ylabel : str
y-axis label.
title : str or None
Subplot title.
color : str or None
Bar fill colour. Falls back to ``PALETTE[0]``.
bar_width : float
Bar width in axes coordinates (0–1 range).
bar_edgecolor : str
Colour of bar borders.
bar_edgewidth : float
Width of bar borders.
show_values : bool
Annotate each bar with its numeric value.
value_fontsize : float
Font size for value annotations.
value_fmt : str
Format string for value annotations (e.g. ``".1f"``, ``".0f"``).
value_color : str
Text colour for value annotations.
show_grid : bool
Show horizontal grid lines.
grid_alpha : float
Grid opacity.
grid_linewidth : float
Grid line thickness.
grid_color : str
Grid line colour.
xtick_rotation : float
Rotation angle for x-tick labels (degrees).
figsize : tuple[float, float]
Figure size in inches.
Returns
-------
plt.Figure
"""
validate_arrays(np.asarray(values), names=["values"])
fig, ax = plt.subplots(figsize=figsize)
c = color or PALETTE[0]
bars = ax.bar(
labels, values, color=c, width=bar_width,
edgecolor=bar_edgecolor, linewidth=bar_edgewidth, zorder=Z_ORDER["data"],
)
# Annotate each bar with its value
if show_values:
for bar in bars:
h = bar.get_height()
ax.text(
bar.get_x() + bar.get_width() / 2,
h + 0.02 * max(values),
format(h, value_fmt),
ha="center", va="bottom", fontsize=value_fontsize,
color=value_color,
)
if xlabel:
ax.set_xlabel(xlabel)
ax.set_ylabel(ylabel)
if title:
ax.set_title(title)
apply_grid(ax, show=show_grid, alpha=grid_alpha, linewidth=grid_linewidth, color=grid_color, axis="y")
ax.tick_params(axis="x", rotation=xtick_rotation)
fig.tight_layout(pad=0.3)
return fig
def grouped_bar_plot(
data: Sequence[dict],
labels: Sequence[str],
*,
xlabel: str | None = None,
ylabel: str = "Value",
title: str | None = None,
bar_width_ratio: float = 0.7,
bar_edgecolor: str = "white",
bar_edgewidth: float = 0.5,
show_grid: bool = True,
grid_alpha: float = GRID_ALPHA,
grid_linewidth: float = GRID_LINEWIDTH,
grid_color: str = GRID_COLOR,
legend_loc: str = "best",
figsize: tuple[float, float] = FIGSIZES["wide_large"],
) -> plt.Figure:
"""Grouped (side-by-side) bar chart for comparing multiple series.
Each dict in *data* may contain:
========== ============ =============================================
Key Required Description
========== ============ =============================================
``values`` Yes 1-D array of bar heights, length matches *labels*.
``label`` No Legend label (default ``"Series N"``).
``color`` No Hex colour (auto-cycled if omitted).
========== ============ =============================================
Parameters
----------
data : sequence of dict
Series definitions (see table above).
labels : sequence of str
Category labels on the x-axis (shared by all series).
xlabel : str or None
x-axis label.
ylabel : str
y-axis label.
title : str or None
Subplot title.
bar_width_ratio : float
Total width of one group relative to 1.0 axis unit.
bar_edgecolor : str
Colour of bar borders.
bar_edgewidth : float
Width of bar borders.
show_grid : bool
Show horizontal grid lines.
grid_alpha, grid_linewidth, grid_color
Grid styling.
legend_loc : str
Legend location.
figsize : tuple[float, float]
Figure size in inches.
Returns
-------
plt.Figure
"""
n_groups = len(labels)
n_series = len(data)
x = np.arange(n_groups)
width = bar_width_ratio / n_series
fig, ax = plt.subplots(figsize=figsize)
for i, ds in enumerate(data):
c = ds.get("color", PALETTE[i % len(PALETTE)])
# Centre the group: offset each series symmetrically around x[k]
offset = (i - (n_series - 1) / 2) * width
ax.bar(
x + offset, ds["values"], width, color=c,
edgecolor=bar_edgecolor, linewidth=bar_edgewidth,
label=ds.get("label", f"Series {i+1}"), zorder=Z_ORDER["data"],
)
ax.set_xticks(x)
ax.set_xticklabels(labels)
if xlabel:
ax.set_xlabel(xlabel)
ax.set_ylabel(ylabel)
if title:
ax.set_title(title)
apply_grid(ax, show=show_grid, alpha=grid_alpha, linewidth=grid_linewidth, color=grid_color, axis="y")
ax.legend(loc=legend_loc)
fig.tight_layout(pad=0.3)
return fig
def stacked_bar_plot(
data: Sequence[dict],
labels: Sequence[str],
*,
xlabel: str | None = None,
ylabel: str = "Value",
title: str | None = None,
bar_width: float = 0.55,
bar_edgecolor: str = "white",
bar_edgewidth: float = 0.5,
show_grid: bool = True,
grid_alpha: float = GRID_ALPHA,
grid_linewidth: float = GRID_LINEWIDTH,
grid_color: str = GRID_COLOR,
legend_loc: str = "best",
figsize: tuple[float, float] = FIGSIZES["wide"],
) -> plt.Figure:
"""Stacked bar chart for part-to-whole composition.
Each dict in *data* may contain:
========== ============ =============================================
Key Required Description
========== ============ =============================================
``values`` Yes 1-D array of segment heights.
``label`` No Legend label.
``color`` No Hex colour (auto-cycled if omitted).
========== ============ =============================================
Parameters
----------
data : sequence of dict
Segment definitions (see table above).
labels : sequence of str
Category labels on the x-axis.
xlabel : str or None
x-axis label.
ylabel : str
y-axis label.
title : str or None
Subplot title.
bar_width : float
Width of each bar group.
bar_edgecolor : str
Colour of bar borders.
bar_edgewidth : float
Width of bar borders.
show_grid : bool
Show horizontal grid lines.
grid_alpha, grid_linewidth, grid_color
Grid styling.
legend_loc : str
Legend location.
figsize : tuple[float, float]
Figure size in inches.
Returns
-------
plt.Figure
"""
x = np.arange(len(labels))
fig, ax = plt.subplots(figsize=figsize)
# Accumulate bottom offset so each segment stacks on the previous one
bottom = np.zeros(len(labels))
for i, ds in enumerate(data):
c = ds.get("color", PALETTE[i % len(PALETTE)])
vals = np.array(ds["values"])
ax.bar(
x, vals, bar_width, bottom=bottom, color=c,
edgecolor=bar_edgecolor, linewidth=bar_edgewidth,
label=ds.get("label", f"Series {i+1}"), zorder=Z_ORDER["data"],
)
bottom += vals # next segment starts here
ax.set_xticks(x)
ax.set_xticklabels(labels)
if xlabel:
ax.set_xlabel(xlabel)
ax.set_ylabel(ylabel)
if title:
ax.set_title(title)
apply_grid(ax, show=show_grid, alpha=grid_alpha, linewidth=grid_linewidth, color=grid_color, axis="y")
ax.legend(loc=legend_loc)
fig.tight_layout(pad=0.3)
return fig