mgplot 0.2.25__py3-none-any.whl → 0.2.26__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.
mgplot/bar_plot.py CHANGED
@@ -42,6 +42,7 @@ class BarKwargs(BaseKwargs):
42
42
  # --- options for the entire bar plot
43
43
  ax: NotRequired[Axes | None]
44
44
  stacked: NotRequired[bool]
45
+ horizontal: NotRequired[bool]
45
46
  max_ticks: NotRequired[int]
46
47
  tick_relabel: NotRequired[Callable[[str], str]]
47
48
  plot_from: NotRequired[int | Period]
@@ -70,7 +71,7 @@ class AnnoKwargs(TypedDict, total=False):
70
71
  fontname: str
71
72
  color: str
72
73
  rotation: int | float
73
- foreground: str # used for stroke effect on text
74
+ foreground: str | Sequence[str] # used for stroke effect on text (per-bar if a sequence)
74
75
  above: bool
75
76
  rounding: bool | int # if True, uses default rounding; if int, uses that value
76
77
 
@@ -80,10 +81,15 @@ def annotate_bars(
80
81
  offset: float,
81
82
  base: np.ndarray,
82
83
  axes: Axes,
84
+ *,
85
+ horizontal: bool = False,
83
86
  **anno_kwargs: Unpack[AnnoKwargs],
84
87
  ) -> None:
85
88
  """Bar plot annotations.
86
89
 
90
+ Annotations are placed along the value axis: the y-axis for vertical
91
+ bars, the x-axis when horizontal=True.
92
+
87
93
  Note: "annotate", "fontsize", "fontname", "color", and "rotation" are expected in anno_kwargs.
88
94
  """
89
95
  # --- only annotate in limited circumstances
@@ -115,18 +121,32 @@ def annotate_bars(
115
121
  position = base[index - zero_correction] + (adjustment if value >= 0 else -adjustment)
116
122
  if above:
117
123
  position += value
124
+ if horizontal:
125
+ placement: dict[str, Any] = {
126
+ "x": position,
127
+ "y": index + offset,
128
+ "ha": "left" if value >= 0 else "right",
129
+ "va": "center",
130
+ }
131
+ else:
132
+ placement = {
133
+ "x": index + offset,
134
+ "y": position,
135
+ "ha": "center",
136
+ "va": "bottom" if value >= 0 else "top",
137
+ }
118
138
  text = axes.text(
119
- x=index + offset,
120
- y=position,
121
139
  s=f"{value:.{rounding}f}",
122
- ha="center",
123
- va="bottom" if value >= 0 else "top",
140
+ **placement,
124
141
  **annotate_style,
125
142
  )
126
143
  if not above and "foreground" in anno_kwargs:
127
144
  # apply a stroke-effect to within bar annotations
128
145
  # to make them more readable with very small bars.
129
- text.set_path_effects([pe.withStroke(linewidth=2, foreground=anno_kwargs.get("foreground"))])
146
+ foreground = anno_kwargs.get("foreground")
147
+ if isinstance(foreground, Sequence) and not isinstance(foreground, str):
148
+ foreground = foreground[index - zero_correction] # per-bar colours
149
+ text.set_path_effects([pe.withStroke(linewidth=2, foreground=foreground)])
130
150
 
131
151
 
132
152
  class GroupedKwargs(TypedDict):
@@ -138,7 +158,14 @@ class GroupedKwargs(TypedDict):
138
158
  zorder: Sequence[int | float | None]
139
159
 
140
160
 
141
- def grouped(axes: Axes, df: DataFrame, anno_args: AnnoKwargs, **kwargs: Unpack[GroupedKwargs]) -> None:
161
+ def grouped(
162
+ axes: Axes,
163
+ df: DataFrame,
164
+ anno_args: AnnoKwargs,
165
+ *,
166
+ horizontal: bool = False,
167
+ **kwargs: Unpack[GroupedKwargs],
168
+ ) -> None:
142
169
  """Plot a grouped bar plot."""
143
170
  series_count = len(df.columns)
144
171
 
@@ -154,20 +181,22 @@ def grouped(axes: Axes, df: DataFrame, anno_args: AnnoKwargs, **kwargs: Unpack[G
154
181
  left = -DEFAULT_BAR_OFFSET + ((1 - width) / 2.0) + (adjusted_width / 2.0)
155
182
  offset = left + (i * adjusted_width)
156
183
  foreground = kwargs["color"][i]
157
- axes.bar(
158
- x=series.index + offset,
159
- height=series,
160
- color=foreground,
161
- width=adjusted_width,
162
- zorder=kwargs["zorder"][i],
163
- label=col if kwargs["label_series"][i] else f"_{col}_",
164
- )
184
+ common: dict[str, Any] = {
185
+ "color": foreground,
186
+ "zorder": kwargs["zorder"][i],
187
+ "label": col if kwargs["label_series"][i] else f"_{col}_",
188
+ }
189
+ if horizontal:
190
+ axes.barh(y=series.index + offset, width=series, height=adjusted_width, **common)
191
+ else:
192
+ axes.bar(x=series.index + offset, height=series, width=adjusted_width, **common)
165
193
  anno_args["foreground"] = foreground
166
194
  annotate_bars(
167
195
  series=series,
168
196
  offset=offset,
169
197
  base=np.zeros(len(series)),
170
198
  axes=axes,
199
+ horizontal=horizontal,
171
200
  **anno_args,
172
201
  )
173
202
 
@@ -181,7 +210,14 @@ class StackedKwargs(TypedDict):
181
210
  zorder: Sequence[int | float | None]
182
211
 
183
212
 
184
- def stacked(axes: Axes, df: DataFrame, anno_args: AnnoKwargs, **kwargs: Unpack[StackedKwargs]) -> None:
213
+ def stacked(
214
+ axes: Axes,
215
+ df: DataFrame,
216
+ anno_args: AnnoKwargs,
217
+ *,
218
+ horizontal: bool = False,
219
+ **kwargs: Unpack[StackedKwargs],
220
+ ) -> None:
185
221
  """Plot a stacked bar plot."""
186
222
  row_count = len(df)
187
223
  base_plus: np.ndarray = np.zeros(shape=row_count, dtype=np.float64)
@@ -190,21 +226,22 @@ def stacked(axes: Axes, df: DataFrame, anno_args: AnnoKwargs, **kwargs: Unpack[S
190
226
  series = df[col]
191
227
  base = np.where(series >= 0, base_plus, base_minus)
192
228
  foreground = kwargs["color"][i]
193
- axes.bar(
194
- x=series.index,
195
- height=series,
196
- bottom=base,
197
- color=foreground,
198
- width=kwargs["width"][i],
199
- zorder=kwargs["zorder"][i],
200
- label=col if kwargs["label_series"][i] else f"_{col}_",
201
- )
229
+ common: dict[str, Any] = {
230
+ "color": foreground,
231
+ "zorder": kwargs["zorder"][i],
232
+ "label": col if kwargs["label_series"][i] else f"_{col}_",
233
+ }
234
+ if horizontal:
235
+ axes.barh(y=series.index, width=series, left=base, height=kwargs["width"][i], **common)
236
+ else:
237
+ axes.bar(x=series.index, height=series, bottom=base, width=kwargs["width"][i], **common)
202
238
  anno_args["foreground"] = foreground
203
239
  annotate_bars(
204
240
  series=series,
205
241
  offset=0,
206
242
  base=base,
207
243
  axes=axes,
244
+ horizontal=horizontal,
208
245
  **anno_args,
209
246
  )
210
247
  base_plus += np.where(series >= 0, series, 0)
@@ -253,12 +290,29 @@ def bar_plot(data: DataT, **kwargs: Unpack[BarKwargs]) -> Axes:
253
290
  # --- set up the default arguments
254
291
  chart_defaults: dict[str, bool | int] = {
255
292
  "stacked": False,
293
+ "horizontal": False,
256
294
  "max_ticks": DEFAULT_MAX_TICKS,
257
295
  "label_series": item_count > 1,
258
296
  "label_rotation": 0,
259
297
  }
260
298
  chart_args = {k: kwargs_d.get(k, v) for k, v in chart_defaults.items()}
261
299
 
300
+ # --- horizontal bars are for categorical data, not PeriodIndex timeseries
301
+ horizontal = bool(chart_args["horizontal"])
302
+ if horizontal and saved_pi is not None:
303
+ print(f"Warning: horizontal=True is not supported with a PeriodIndex in {ME}(); plotting vertical.")
304
+ horizontal = False
305
+
306
+ # --- single series + one colour per bar => per-bar colours
307
+ user_color = kwargs_d.get("color")
308
+ if (
309
+ item_count == 1
310
+ and isinstance(user_color, Sequence)
311
+ and not isinstance(user_color, str)
312
+ and len(user_color) == len(df)
313
+ ):
314
+ kwargs_d["color"] = [list(user_color)] # one series whose colour is a per-bar list
315
+
262
316
  bar_defaults = {
263
317
  "color": get_color_list(item_count),
264
318
  "width": get_setting("bar_width"),
@@ -280,14 +334,18 @@ def bar_plot(data: DataT, **kwargs: Unpack[BarKwargs]) -> Axes:
280
334
  # --- plot the data
281
335
  axes, remaining_kwargs = get_axes(**dict(remaining_kwargs))
282
336
  if chart_args["stacked"]:
283
- stacked(axes, df, anno_args, **bar_args)
337
+ stacked(axes, df, anno_args, horizontal=horizontal, **bar_args)
284
338
  else:
285
- grouped(axes, df, anno_args, **bar_args)
339
+ grouped(axes, df, anno_args, horizontal=horizontal, **bar_args)
286
340
 
287
341
  # --- handle index labels and rotation
288
342
  if saved_strings is not None:
289
- axes.set_xticks(range(len(saved_strings[1])))
290
- axes.set_xticklabels(saved_strings[1], rotation=chart_args["label_rotation"])
343
+ if horizontal:
344
+ axes.set_yticks(range(len(saved_strings[1])))
345
+ axes.set_yticklabels(saved_strings[1], rotation=chart_args["label_rotation"])
346
+ else:
347
+ axes.set_xticks(range(len(saved_strings[1])))
348
+ axes.set_xticklabels(saved_strings[1], rotation=chart_args["label_rotation"])
291
349
  elif saved_pi is not None:
292
350
  set_labels(
293
351
  axes,
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: mgplot
3
- Version: 0.2.25
3
+ Version: 0.2.26
4
4
  Summary: mgplot is a time-series/PeriodIndex frontend for matplotlib
5
5
  Project-URL: Repository, https://github.com/bpalmer4/mgplot
6
6
  Project-URL: Homepage, https://github.com/bpalmer4/mgplot
@@ -68,8 +68,9 @@ All plot functions take a pandas Series or DataFrame with a PeriodIndex
68
68
  as the first argument and return a matplotlib Axes object. Keyword
69
69
  arguments control styling and behavior:
70
70
 
71
- - `bar_plot()` -- vertical bar plot (grouped or stacked) with intelligent
72
- PeriodIndex labeling
71
+ - `bar_plot()` -- bar plot (grouped or stacked) with intelligent
72
+ PeriodIndex labeling; `horizontal=True` plots categorical data as
73
+ horizontal bars (categories on the y-axis, values along the x-axis)
73
74
  - `fill_between_plot()` -- shaded region between two bounds (requires
74
75
  2-column DataFrame)
75
76
  - `growth_plot()` -- plots annual and periodic growth rates (requires
@@ -85,6 +86,25 @@ arguments control styling and behavior:
85
86
  - `summary_plot()` -- latest data point against historical range with
86
87
  z-score visualization
87
88
 
89
+ For ranked-category charts (states, industries, expenditure classes),
90
+ use `horizontal=True` with a string-indexed Series or DataFrame:
91
+
92
+ ```python
93
+ vacancies = vacancies.sort_values() # smallest at the bottom
94
+ mg.bar_plot_finalise(
95
+ vacancies,
96
+ horizontal=True,
97
+ annotate=True, # value labels at the bar ends
98
+ above=True,
99
+ x0=True, # zero line on the value axis
100
+ title="Job vacancies by industry",
101
+ xlabel="'000",
102
+ )
103
+ ```
104
+
105
+ `horizontal=True` is for categorical data: with a PeriodIndex it warns
106
+ and falls back to a vertical plot.
107
+
88
108
  Finalising Plots
89
109
  ----------------
90
110
  Once a plot is generated, finalise it with titles, labels, and save to file:
@@ -1,6 +1,6 @@
1
1
  mgplot/__init__.py,sha256=J3CQX5UXrGXrfs-YWpbzHA_sz1HJ5438xNM0V36x1vo,3164
2
2
  mgplot/axis_utils.py,sha256=LWKpSRwnxcwQiq83-W4tBCMj8j9SPsfvcWioA0lapdU,15960
3
- mgplot/bar_plot.py,sha256=D2R_MBPVvLdWYobleNwfblcWG05sfY19GBxBjgfVyIg,10317
3
+ mgplot/bar_plot.py,sha256=FobAsadYSEf-U0RZFgZutTzse4Rgr0TDFyWUMM68JVs,12513
4
4
  mgplot/colors.py,sha256=f5q4z7kORUu66uAxNeK9KAZ64gv_7h_x2qH53BvzwPw,4848
5
5
  mgplot/fill_between_plot.py,sha256=XJvtkBeOkohHyayQnu84jURapB5RsMAR-3SaskHkHfM,3361
6
6
  mgplot/finalise_plot.py,sha256=WHk06vOZwMjP0cwA-FXl7sLn10hLZNQLBWqMXPgwF4o,15627
@@ -18,7 +18,7 @@ mgplot/seastrend_plot.py,sha256=hi9t0cY0bHdIOU5abLMX7qvAp_hlVLlJFyEKNBzg6Ts,2000
18
18
  mgplot/settings.py,sha256=co0cElVIdmkfftQrMg4MviyV5TSmvNOzaUN_h_RrjOY,5583
19
19
  mgplot/summary_plot.py,sha256=Kg7VD8KFIls4KlD4jeaaXnDw51BZ3p_wMAUpjG49zGQ,11102
20
20
  mgplot/utilities.py,sha256=Rouc76vwjL49nVgAzymzoOyX6GrBqp-sjELHalBD_Qo,8445
21
- mgplot-0.2.25.dist-info/METADATA,sha256=RsZ_e7Fd4Xj1tlV2MNFfxZHM0WlBHK5P48tjLMtiCZE,7256
22
- mgplot-0.2.25.dist-info/WHEEL,sha256=mffPy8wBnZQn2VnJUU5jE99KsxaSfiyMHV9Yt0aLVxs,87
23
- mgplot-0.2.25.dist-info/licenses/LICENSE,sha256=6ZyruOwF8J7mY25-vZHdOibtY8cSNLz0vWeH59TLhtw,1082
24
- mgplot-0.2.25.dist-info/RECORD,,
21
+ mgplot-0.2.26.dist-info/METADATA,sha256=yKmPAjfQee0xcWo8P5QZoadTse2gMbJ-_UXK875lDJg,7923
22
+ mgplot-0.2.26.dist-info/WHEEL,sha256=mffPy8wBnZQn2VnJUU5jE99KsxaSfiyMHV9Yt0aLVxs,87
23
+ mgplot-0.2.26.dist-info/licenses/LICENSE,sha256=6ZyruOwF8J7mY25-vZHdOibtY8cSNLz0vWeH59TLhtw,1082
24
+ mgplot-0.2.26.dist-info/RECORD,,