mgplot 0.2.32__py3-none-any.whl → 0.2.34__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/__init__.py CHANGED
@@ -103,7 +103,6 @@ __all__ = (
103
103
  "revision_plot",
104
104
  "revision_plot_finalise",
105
105
  "run_plot",
106
- "run_plot",
107
106
  "run_plot_finalise",
108
107
  "seastrend_plot",
109
108
  "seastrend_plot_finalise",
@@ -21,6 +21,11 @@ Algorithm (everything is computed in display/pixel coordinates):
21
21
  end-of-axes labels. The stack keeps the labels in the same vertical order as
22
22
  the line ends they belong to (isotonic placement), so annotations for lines
23
23
  that finish close together never read out of order.
24
+ * A near-end label that did fit locally but collides with the stack's layout
25
+ joins the stack (repeatedly, as each join re-lays it), rather than being
26
+ jumped over. Near-end labels nothing collides with are left untouched.
27
+ * Stack labels far enough apart not to touch form separate sub-stacks: each
28
+ clears any remaining obstacle on its own, so one pile-up never drags another.
24
29
  * An interior label that cannot be cleared keeps the candidate position with the
25
30
  most clearance -- overlap is accepted rather than moving it off its line end.
26
31
  * Line avoidance never applies to a label sitting at the last data point: its
@@ -242,42 +247,52 @@ def _stack_shift(stack: list[dict[str, Any]], ys: list[float], placed: list[dict
242
247
  return 0.0
243
248
 
244
249
 
245
- def _stack_snapped(
246
- stack: list[dict[str, Any]],
247
- placed: list[dict[str, Any]],
248
- right_disp_x: float,
249
- ) -> None:
250
- """Snap labels to the rightmost data point, stacked in line-end order.
250
+ def _snap_x(lab: dict[str, Any], right_disp_x: float) -> None:
251
+ """Move a label's box across to the rightmost data point."""
252
+ delta = right_disp_x - lab["x0"]
253
+ lab["x0"] += delta
254
+ lab["x1"] += delta
255
+ lab["snapped"] = True
256
+
257
+
258
+ def _sep(lower: dict[str, Any], upper: dict[str, Any]) -> float:
259
+ """Minimum centre-to-centre separation between two stacked labels."""
260
+ return (lower["h"] + upper["h"]) / 2.0 + _GAP_PX
251
261
 
252
- The vertical order of the stack matches the order of the line ends it
253
- annotates, so labels for lines that finish close together never swap.
254
- Within that constraint the labels sit as near their own line end as the
255
- minimum separation allows.
256
- """
257
- if not stack:
258
- return
259
- for lab in stack:
260
- delta = right_disp_x - lab["x0"]
261
- lab["x0"] += delta
262
- lab["x1"] += delta
263
- lab["snapped"] = True
264
262
 
263
+ def _stack_layout(stack: list[dict[str, Any]]) -> list[float]:
264
+ """Sort the stack into line-end order and return each label's ideal centre y.
265
+
266
+ The vertical order matches the order of the line ends annotated, so labels
267
+ for lines that finish close together never swap. Within that constraint
268
+ the labels sit as near their own line end as the minimum separation allows.
269
+ """
265
270
  stack.sort(key=lambda lab: lab["anchor_yc"]) # bottom-most line end first
266
271
  # Subtracting the cumulative minimum separation turns "stay this far apart,
267
272
  # in this order" into plain "non-decreasing", which _isotonic() solves.
268
273
  cums: list[float] = []
269
- cum, prev_h = 0.0, None
270
- for lab in stack:
271
- if prev_h is not None:
272
- cum += (prev_h + lab["h"]) / 2.0 + _GAP_PX
274
+ cum = 0.0
275
+ for i, lab in enumerate(stack):
276
+ if i:
277
+ cum += _sep(stack[i - 1], lab)
273
278
  cums.append(cum)
274
- prev_h = lab["h"]
275
279
  fitted = _isotonic([lab["anchor_yc"] - c for lab, c in zip(stack, cums, strict=True)])
276
- ys = [f + c for f, c in zip(fitted, cums, strict=True)]
280
+ return [f + c for f, c in zip(fitted, cums, strict=True)]
281
+
277
282
 
278
- shift = _stack_shift(stack, ys, placed)
279
- for lab, y in zip(stack, ys, strict=True):
280
- lab["yc"] = y + shift
283
+ def _stack_groups(
284
+ stack: list[dict[str, Any]],
285
+ ys: list[float],
286
+ ) -> list[tuple[list[dict[str, Any]], list[float]]]:
287
+ """Split a laid-out stack into runs of touching labels (independent sub-stacks)."""
288
+ groups: list[tuple[list[dict[str, Any]], list[float]]] = []
289
+ for i, (lab, y) in enumerate(zip(stack, ys, strict=True)):
290
+ if i and y - ys[i - 1] <= _sep(stack[i - 1], lab) + _STEP_PX:
291
+ groups[-1][0].append(lab)
292
+ groups[-1][1].append(y)
293
+ else:
294
+ groups.append(([lab], [y]))
295
+ return groups
281
296
 
282
297
 
283
298
  def _root_figure(axes: Axes) -> Figure:
@@ -388,12 +403,49 @@ def _place_all(
388
403
  placed.append(lab)
389
404
 
390
405
  stack: list[dict[str, Any]] = []
406
+ local: list[dict[str, Any]] = []
391
407
  for lab in sorted(cluster, key=lambda lab: (-lab["x_data"], lab["yc"])):
392
408
  if not force_right and _place_cluster_local(lab, placed, others(lab)):
393
409
  placed.append(lab)
410
+ local.append(lab)
394
411
  else:
395
412
  stack.append(lab) # laid out together below, so their order is kept
396
- _stack_snapped(stack, placed, right_disp_x)
413
+ _resolve_stack(stack, local, placed, right_disp_x)
414
+
415
+
416
+ def _resolve_stack(
417
+ stack: list[dict[str, Any]],
418
+ local: list[dict[str, Any]],
419
+ placed: list[dict[str, Any]],
420
+ right_disp_x: float,
421
+ ) -> None:
422
+ """Snap the stack to the right edge, absorbing the local labels it collides with."""
423
+ for lab in stack:
424
+ _snap_x(lab, right_disp_x)
425
+
426
+ # A local label that the stack's ideal layout collides with joins the stack,
427
+ # rather than being jumped over (which would read out of line-end order).
428
+ # Repeat, as each join re-lays the stack. Local labels nothing collides
429
+ # with are left exactly where they are.
430
+ while True:
431
+ ys = _stack_layout(stack)
432
+ joins = [p for p in local if any(_hits_label(lab, y, [p]) for lab, y in zip(stack, ys, strict=True))]
433
+ if not joins:
434
+ break
435
+ for p in joins:
436
+ _snap_x(p, right_disp_x)
437
+ stack.extend(joins)
438
+ ids = {id(p) for p in joins}
439
+ local = [p for p in local if id(p) not in ids]
440
+ placed = [p for p in placed if id(p) not in ids]
441
+
442
+ # Separate pile-ups are separate sub-stacks: each clears any remaining
443
+ # (interior) obstacle on its own, so one pile-up never drags another.
444
+ for group, gys in _stack_groups(stack, ys):
445
+ shift = _stack_shift(group, gys, placed)
446
+ for lab, y in zip(group, gys, strict=True):
447
+ lab["yc"] = y + shift
448
+ placed.extend(group)
397
449
 
398
450
 
399
451
  def _draw_leaders(axes: Axes, labels: list[dict[str, Any]], trans: Transform) -> None:
mgplot/axis_utils.py CHANGED
@@ -19,7 +19,7 @@ from pandas.api.types import is_string_dtype
19
19
  from mgplot.settings import DataT
20
20
 
21
21
 
22
- def map_stringindex(data: DataT) -> None | tuple[DataT, list[str]]:
22
+ def map_stringindex(data: DataT) -> tuple[DataT, list[str]] | None:
23
23
  """Map a string (object) index to an integer RangeIndex.
24
24
 
25
25
  Returns None if the index is not a string/object type.
@@ -92,12 +92,12 @@ def register_period_axes(axes: Axes, p: PeriodIndex) -> None:
92
92
  )
93
93
 
94
94
 
95
- def get_period_axes(axes: Axes) -> None | tuple[str, int, int]:
95
+ def get_period_axes(axes: Axes) -> tuple[str, int, int] | None:
96
96
  """Return the stashed (freq, min_ordinal, max_ordinal) for an axes, or None."""
97
97
  return getattr(axes, _AXES_PERIOD_ATTR, None)
98
98
 
99
99
 
100
- def map_periodindex(data: DataT) -> None | tuple[DataT, PeriodIndex]:
100
+ def map_periodindex(data: DataT) -> tuple[DataT, PeriodIndex] | None:
101
101
  """Map a PeriodIndex to an integer index."""
102
102
  if not isinstance(data.index, PeriodIndex):
103
103
  return None
mgplot/finalise_plot.py CHANGED
@@ -153,7 +153,7 @@ def sanitize_filename(filename: str, max_length: int = MAX_FILENAME_LENGTH) -> s
153
153
  return filename or "untitled"
154
154
 
155
155
 
156
- def make_legend(axes: Axes, *, legend: None | bool | dict[str, Any]) -> None:
156
+ def make_legend(axes: Axes, *, legend: bool | dict[str, Any] | None) -> None:
157
157
  """Create a legend for the plot."""
158
158
  if legend is None or legend is False:
159
159
  return
mgplot/line_plot.py CHANGED
@@ -44,7 +44,7 @@ class LineKwargs(BaseKwargs):
44
44
  markersize: NotRequired[float | Sequence[float] | int | None]
45
45
  zorder: NotRequired[int | float | Sequence[int | float]]
46
46
  dropna: NotRequired[bool | Sequence[bool]]
47
- annotate: NotRequired[bool | Sequence[bool]]
47
+ annotate: NotRequired[bool | str | Sequence[bool | str]]
48
48
  rounding: NotRequired[Sequence[int | bool] | int | bool | None]
49
49
  fontsize: NotRequired[Sequence[str | int | float] | str | int | float]
50
50
  fontname: NotRequired[str | Sequence[str]]
@@ -67,6 +67,7 @@ class AnnotateKwargs(TypedDict):
67
67
  fontsize: str | int | float
68
68
  fontname: str
69
69
  rotation: int | float
70
+ text: str | None
70
71
 
71
72
 
72
73
  # --- functions
@@ -77,6 +78,11 @@ def annotate_series(
77
78
  ) -> Text | None:
78
79
  """Annotate the right-hand end-point of a line-plotted series.
79
80
 
81
+ The label text is the `text` keyword argument when that is a string,
82
+ otherwise the end-point value rounded to `rounding` places. Either way the
83
+ series must have a numeric end-point, which is what the label is anchored
84
+ to.
85
+
80
86
  Returns the created Text artist (or None if there was nothing to annotate)
81
87
  so the caller can register it for end-of-line collision resolution.
82
88
  """
@@ -100,8 +106,12 @@ def annotate_series(
100
106
  color = kwargs.get("color")
101
107
  if color is None:
102
108
  raise ValueError("color is required for annotation")
103
- rounding = default_rounding(value=y, provided=kwargs.get("rounding"))
104
- r_string = f" {y:.{rounding}f}" if rounding > 0 else f" {int(y)}"
109
+ text = kwargs.get("text")
110
+ if isinstance(text, str):
111
+ r_string = f" {text}"
112
+ else:
113
+ rounding = default_rounding(value=y, provided=kwargs.get("rounding"))
114
+ r_string = f" {y:.{rounding}f}" if rounding > 0 else f" {int(y)}"
105
115
  return axes.text(
106
116
  x=x,
107
117
  y=y,
@@ -166,6 +176,17 @@ def line_plot(data: DataT, **kwargs: Unpack[LineKwargs]) -> Axes:
166
176
  data: DataFrame | Series - data to plot
167
177
  kwargs: LineKwargs - keyword arguments for the line plot
168
178
 
179
+ The annotate key labels the right-hand end of each line. It takes either a
180
+ flag or a string, as a scalar broadcast to every series or as a per-series
181
+ sequence:
182
+ annotate=True - label with the end-point value (default
183
+ behaviour)
184
+ annotate="26Q2" - label every series with that text
185
+ annotate=["26Q2", "26Q3"] - label each series with its own text
186
+ annotate=False (or "") - no label
187
+ A string label is printed as given, so rounding has no effect on it;
188
+ annotate_color still applies and remains the way to colour the label.
189
+
169
190
  Returns:
170
191
  - axes: Axes - the axes object for the plot
171
192
 
@@ -236,6 +257,7 @@ def line_plot(data: DataT, **kwargs: Unpack[LineKwargs]) -> Axes:
236
257
  fontsize=swce["fontsize"][i],
237
258
  fontname=swce["fontname"][i],
238
259
  rotation=swce["rotation"][i],
260
+ text=swce["annotate"][i],
239
261
  )
240
262
  if text is not None:
241
263
  annotations.append((text, lines[0] if lines else None))
mgplot/multi_plot.py CHANGED
@@ -214,7 +214,7 @@ def plot_then_finalise(
214
214
  def multi_start(
215
215
  data: DataT,
216
216
  function: Callable | list[Callable],
217
- starts: Iterable[None | Period | int],
217
+ starts: Iterable[Period | int | None],
218
218
  **kwargs: Any,
219
219
  ) -> None:
220
220
  """Create multiple plots with different starting points.
mgplot/run_plot.py CHANGED
@@ -142,8 +142,9 @@ def _plot_runs(
142
142
 
143
143
  # Create annotation text
144
144
  rounding = kwargs.get("rounding", DEFAULT_ROUNDING)
145
+ digits = rounding if isinstance(rounding, int) else DEFAULT_ROUNDING
145
146
  total_change = change_points[stretch.index].sum()
146
- annotation_text = f"{total_change.round(rounding)} pp"
147
+ annotation_text = f"{round(float(total_change), digits)} pp"
147
148
 
148
149
  text = axes.text(
149
150
  x=stretch.index.min(),
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: mgplot
3
- Version: 0.2.32
3
+ Version: 0.2.34
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
@@ -1,25 +1,25 @@
1
- mgplot/__init__.py,sha256=J3CQX5UXrGXrfs-YWpbzHA_sz1HJ5438xNM0V36x1vo,3164
2
- mgplot/annotation_utils.py,sha256=nlR1J_0b9HD7d3sL1oyNmhiIyI2Xp6cgKW5fwWDRSaI,18567
3
- mgplot/axis_utils.py,sha256=-wnjUTL2MdwEntLEVihDABOxLSbux0aSyATCnIsVumg,16041
1
+ mgplot/__init__.py,sha256=a_tWH1ldgIJtaHOlFEjNSU6EeSSEMt9I7IcN5yOBZfM,3148
2
+ mgplot/annotation_utils.py,sha256=p0iju88_QGsfzttK3sn53DwF4hD3ZXiCJVkE6RENovw,20972
3
+ mgplot/axis_utils.py,sha256=iJlTDplmc2uaoRHYYMxE3miCTmm6Q_ufg2BFSZce-TI,16041
4
4
  mgplot/bar_plot.py,sha256=FobAsadYSEf-U0RZFgZutTzse4Rgr0TDFyWUMM68JVs,12513
5
5
  mgplot/colors.py,sha256=f5q4z7kORUu66uAxNeK9KAZ64gv_7h_x2qH53BvzwPw,4848
6
6
  mgplot/fill_between_plot.py,sha256=XJvtkBeOkohHyayQnu84jURapB5RsMAR-3SaskHkHfM,3361
7
- mgplot/finalise_plot.py,sha256=ttrSy2noxF4EyFlYZJUjy1LICFFE0IuF_26HreeMD1k,24456
7
+ mgplot/finalise_plot.py,sha256=8NGi2SFAABrP1vjKpHcug8OS6jWWpHErwq1mif6qCCg,24456
8
8
  mgplot/finalisers.py,sha256=Wozq4XOmnMdhEB9LJqHao9TrleOfhNV54kRa_bgN-e8,10547
9
9
  mgplot/growth_plot.py,sha256=QALNYyINd_u7BL3q-My16eRuhq0LzGfawu-_MsVOXl0,8708
10
10
  mgplot/keyword_checking.py,sha256=8CFexwEK_Uyv3_8hAnJ2ewk0tEjNjkwzKfX2uFw2UpM,11446
11
- mgplot/line_plot.py,sha256=Glajqp5lDIKKt5V-AwVhn84BvdfPSzJme1s3BnGqJD8,9175
11
+ mgplot/line_plot.py,sha256=GWOhRpTT-GEMo1m4NWnm2jURqDWf5j8pF6ICVsoIPSE,10224
12
12
  mgplot/lint-all.sh,sha256=O7ns09v0cQNQ6POWtXtYn6VdtYURHTjy06vntR8tr_U,465
13
- mgplot/multi_plot.py,sha256=8tiUXe1UJGyPvHp3ox2CQ5b-KjdSV9y5avI_70uJFMk,10699
13
+ mgplot/multi_plot.py,sha256=WCTefA15L4FLZJj3Tq-4mQc4JaraBEoRYSV0gTZ81eQ,10699
14
14
  mgplot/postcovid_plot.py,sha256=TR3BY_1CbIR2IRvlqqbqhhacEyUMDZIEL-mcLs9FV3U,8716
15
15
  mgplot/py.typed,sha256=AbpHGcgLb-kRsJGnwFEktk7uzpZOCcBY74-YBdrKVGs,1
16
16
  mgplot/revision_plot.py,sha256=GC4h-7VKBkA0wdvbzsRtOdexdjJBrqZ6cDtGaq-65LE,2238
17
- mgplot/run_plot.py,sha256=tG5YbAZ11WEBw9Jxanpp1W5E-q3sMUd5VjD7yIxrgY8,7355
17
+ mgplot/run_plot.py,sha256=JYNaUh_ghCa5YFE4q2qiRgXcwI9Z73OZiKbg-9fnK9o,7438
18
18
  mgplot/seastrend_plot.py,sha256=hi9t0cY0bHdIOU5abLMX7qvAp_hlVLlJFyEKNBzg6Ts,2000
19
19
  mgplot/settings.py,sha256=RhxgX4d-CgRpvs-ALG_j8tg3wwHSyfvFNdL0aMjofA0,5584
20
20
  mgplot/summary_plot.py,sha256=Kg7VD8KFIls4KlD4jeaaXnDw51BZ3p_wMAUpjG49zGQ,11102
21
21
  mgplot/utilities.py,sha256=PfzThb_nXYIMhnprQzNcaBqUZV8ysHJte0TU7TIis00,8450
22
- mgplot-0.2.32.dist-info/METADATA,sha256=qvq5qkI_HneUX7yrF4yvElE8piLhtTKvtfcwZVQ_apw,7923
23
- mgplot-0.2.32.dist-info/WHEEL,sha256=zOwg4jB6zX2kU910N-cMawjivD6tO8NEWvE12je1bVk,87
24
- mgplot-0.2.32.dist-info/licenses/LICENSE,sha256=6ZyruOwF8J7mY25-vZHdOibtY8cSNLz0vWeH59TLhtw,1082
25
- mgplot-0.2.32.dist-info/RECORD,,
22
+ mgplot-0.2.34.dist-info/METADATA,sha256=OAPwXOvfVAMmVrHQ-L9ld9cwM29SDGT89eaJrKvosnc,7923
23
+ mgplot-0.2.34.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
24
+ mgplot-0.2.34.dist-info/licenses/LICENSE,sha256=6ZyruOwF8J7mY25-vZHdOibtY8cSNLz0vWeH59TLhtw,1082
25
+ mgplot-0.2.34.dist-info/RECORD,,
@@ -1,4 +1,4 @@
1
1
  Wheel-Version: 1.0
2
- Generator: hatchling 1.32.0
2
+ Generator: hatchling 1.32.4
3
3
  Root-Is-Purelib: true
4
4
  Tag: py3-none-any