@dsh-ft/dsh-fft-plot 0.1.0 → 0.2.0

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.
@@ -2,7 +2,9 @@
2
2
 
3
3
  新增一种图,只做两件事:
4
4
 
5
- 1. 在下面写一个函数并加 `@chart('名字')` 装饰器;
5
+ 1. 在下面写一个函数并加 `@chart('名字', x_axis=True)` 装饰器:
6
+ `x_axis=True` 表示图型自己会在绘图区下方画横轴标签,`plot.py` 会据此预留高度;
7
+ 不声明就会把标签画进说明区(旧版这里靠一张写死的图型名单)。
6
8
  2. 在 SKILL.md 的图型表里加一行(给模型看的字段说明)。
7
9
 
8
10
  函数签名固定为 `(c, rect, cfg, rows)`:
@@ -13,25 +15,54 @@
13
15
  - `rows` —— 数据行 `list[dict]`
14
16
 
15
17
  约定:**列名缺失或类型不符必须报错**,绝不静默丢行——金融图上少一根线而不报错,
16
- 比直接失败更危险。颜色用 `resolve_color()`,既接受主题键也接受 `#RRGGBB`。
18
+ 比直接失败更危险。数值列不接受 NaN/Infinity(会写出非法 SVG 坐标);确实要表示
19
+ “没有数据”的间隙时用 JSON `null`,并且该图型要显式允许(如 line 的 series/band)。
20
+ 颜色用 `resolve_color()`,既接受主题键也接受 `#RRGGBB`。
17
21
  """
18
22
  import math
19
23
 
20
- from .canvas import (Axes, fmt_compact, fmt_date_label, fmt_num, fmt_pct, has_multiple_years,
21
- nice_ticks, text_width)
24
+ from .canvas import (Axes, contrast_ink, date_parts, fmt_compact, fmt_date_label, fmt_num,
25
+ fmt_pct, has_multiple_years, mix_hex, nice_ticks, text_width)
26
+ from .theme import series_color
22
27
 
23
28
  #: 图型注册表。键是 `chart.type` 的取值。
24
29
  CHARTS = {}
25
30
 
31
+ #: 图型元数据:是否自绘横轴、横轴需要多高。布局层只认这里,不认图型名字。
32
+ CHART_META = {}
26
33
 
27
- def chart(name):
28
- """把一个函数登记成 `chart.type = name` 的渲染器。"""
34
+
35
+ def chart(name, *, x_axis=False, x_axis_height=None, needs_rows=True):
36
+ """把一个函数登记成 `chart.type = name` 的渲染器。
37
+
38
+ `x_axis=True` 时 `plot.py` 会在绘图区下方留出横轴标签的高度(默认 46px);
39
+ `needs_rows=False` 用于示意图这类不消费数据行的图型(此时 spec 可以不写 rows/data)。
40
+ """
29
41
  def deco(fn):
30
42
  CHARTS[name] = fn
43
+ CHART_META[name] = {'x_axis': bool(x_axis), 'x_axis_height': x_axis_height,
44
+ 'needs_rows': bool(needs_rows)}
31
45
  return fn
32
46
  return deco
33
47
 
34
48
 
49
+ def needs_x_axis(kind):
50
+ """该图型是否自绘横轴标签。未知图型返回 False(真正的报错在 render 里)。"""
51
+ return CHART_META.get(kind, {}).get('x_axis', False)
52
+
53
+
54
+ def needs_rows(kind):
55
+ """该图型是否必须有数据行(示意图为 False)。"""
56
+ return CHART_META.get(kind, {}).get('needs_rows', True)
57
+
58
+
59
+ def x_axis_height(kind, default=46):
60
+ """该图型需要预留的横轴高度;不需要横轴时为 0。"""
61
+ if not needs_x_axis(kind):
62
+ return 0
63
+ return CHART_META.get(kind, {}).get('x_axis_height') or default
64
+
65
+
35
66
  def render(c, rect, cfg, rows):
36
67
  """按 `cfg['type']` 分派。未知类型列出全部可用值,便于直接改正。"""
37
68
  kind = cfg.get('type')
@@ -39,7 +70,7 @@ def render(c, rect, cfg, rows):
39
70
  raise ValueError("chart.type is required; available: " + ", ".join(sorted(CHARTS)))
40
71
  if kind not in CHARTS:
41
72
  raise KeyError(f"unknown chart.type {kind!r}; available: " + ", ".join(sorted(CHARTS)))
42
- if not rows:
73
+ if not rows and needs_rows(kind):
43
74
  raise ValueError(f'chart type {kind!r} needs rows, but the data is empty')
44
75
  return CHARTS[kind](c, rect, cfg, rows)
45
76
 
@@ -57,16 +88,31 @@ def column(rows, name):
57
88
  return out
58
89
 
59
90
 
60
- def numbers(rows, name):
61
- """取数值列。数值字符串按数值处理,无法转换则报错。"""
91
+ def numbers(rows, name, allow_none=False):
92
+ """取数值列。
93
+
94
+ - 默认:遇 `None`、布尔或无法转换的值直接报错(含行号);
95
+ - `allow_none=True`:`None` 作为“没有数据”的间隙保留,`NaN/Infinity` 仍报错;
96
+ - 数值字符串按数值处理。
97
+ """
62
98
  out = []
63
99
  for i, value in enumerate(column(rows, name)):
64
- if isinstance(value, bool) or value is None:
100
+ if value is None:
101
+ if allow_none:
102
+ out.append(None)
103
+ continue
104
+ raise TypeError(f'column {name!r} is None at row {i}; '
105
+ 'pass null only for charts that accept gaps')
106
+ if isinstance(value, bool):
65
107
  raise TypeError(f'column {name!r} is not numeric at row {i}: {value!r}')
66
108
  try:
67
- out.append(float(value))
109
+ number = float(value)
68
110
  except (TypeError, ValueError):
69
111
  raise TypeError(f'column {name!r} is not numeric at row {i}: {value!r}') from None
112
+ if not math.isfinite(number):
113
+ raise ValueError(f'column {name!r} is not finite at row {i}: {value!r}; '
114
+ 'NaN/Infinity cannot be drawn')
115
+ out.append(number)
70
116
  return out
71
117
 
72
118
 
@@ -85,7 +131,7 @@ def resolve_color(theme, token, default='down'):
85
131
 
86
132
 
87
133
  def padded_domain(*groups, include_zero=True, pad=0.10):
88
- """由若干组数值算 y 轴范围,留出上下留白。"""
134
+ """由若干组数值算 y 轴范围,留出上下留白。`None` 视为缺测跳过。"""
89
135
  values = [v for group in groups for v in group if v is not None and math.isfinite(v)]
90
136
  if not values:
91
137
  return (0.0, 1.0)
@@ -98,6 +144,52 @@ def padded_domain(*groups, include_zero=True, pad=0.10):
98
144
  return (lo - span * pad, hi + span * pad)
99
145
 
100
146
 
147
+ def _formatter(kind, dec, signed=False):
148
+ """按 `fmt` 生成格式化函数;`signed=True` 时正数带 `+`。"""
149
+ if kind == 'pct':
150
+ return lambda value: fmt_pct(value, dec, signed=signed)
151
+ if kind == 'compact':
152
+ base = lambda value: fmt_compact(value, dec or 1) # noqa: E731
153
+ else:
154
+ base = lambda value: fmt_num(value, dec) # noqa: E731
155
+ if signed:
156
+ return lambda value: ('+' if value > 0 else '') + base(value)
157
+ return base
158
+
159
+
160
+ def _ellipsis(text, size, max_width):
161
+ """按估算宽度截断并加省略号,避免长标签压到图形上。"""
162
+ if text_width(text, size) <= max_width:
163
+ return text
164
+ cut = text
165
+ while cut and text_width(cut + '…', size) > max_width:
166
+ cut = cut[:-1]
167
+ return cut + '…'
168
+
169
+
170
+ def _segments(points):
171
+ """把带 `None` 的点列切成连续段,用于折线/面积跨过缺测。"""
172
+ segments, current = [], []
173
+ for point in points:
174
+ if point is None:
175
+ if current:
176
+ segments.append(current)
177
+ current = []
178
+ else:
179
+ current.append(point)
180
+ if current:
181
+ segments.append(current)
182
+ return segments
183
+
184
+
185
+ def _decimals_for_step(step):
186
+ """刻度步长需要的小数位:0.25 → 2,2 → 0。"""
187
+ if not step or not math.isfinite(step):
188
+ return 0
189
+ text = f'{abs(step):.10f}'.rstrip('0').rstrip('.')
190
+ return len(text.split('.')[1]) if '.' in text else 0
191
+
192
+
101
193
  class XAxis:
102
194
  """x 轴。
103
195
 
@@ -177,16 +269,27 @@ class XAxis:
177
269
  return picked
178
270
 
179
271
 
272
+ def _flush_band(c, run, color, opacity):
273
+ """把一段连续的上/下边界围成多边形。"""
274
+ if len(run) < 2:
275
+ return
276
+ upper = [(px, upper) for px, upper, _ in run]
277
+ lower = [(px, lower) for px, _, lower in reversed(run)]
278
+ c.polygon(upper + lower, color, opacity=opacity)
279
+
280
+
180
281
  # ---------------------------------------------------------------- line
181
282
 
182
- @chart('line')
283
+ @chart('line', x_axis=True)
183
284
  def line(c, rect, cfg, rows):
184
285
  """时序折线。
185
286
 
186
287
  字段:`x`(x 列名)、`series`(必填,`[{col,label,color,dash}]`)、
187
288
  `band`(可选 `{lo,hi,label,color}`)、`refs`(可选 `[{y,label,color}]`)、
188
289
  `marks`(可选,要打点的 x 值列表)、`annotate`(可选 `[{x,text,color,dy}]`)、
189
- `y_fmt`(`num`/`pct`)、`y_dec`(小数位)。
290
+ `y_fmt`(`num`/`pct`/`compact`)、`y_dec`(小数位,按刻度自动补足)、
291
+ `include_zero`(默认 false;水平/资金类数据显式设 true)。
292
+ `series`/`band` 的值允许 JSON `null`,表示该点没有数据。
190
293
  """
191
294
  x_col = cfg.get('x')
192
295
  if x_col is None:
@@ -197,67 +300,115 @@ def line(c, rect, cfg, rows):
197
300
 
198
301
  xaxis = XAxis(column(rows, x_col), kind=cfg.get('x_kind', 'auto'))
199
302
  n = len(xaxis)
200
- series = [{'label': s.get('label', s['col']), 'col': s['col'],
201
- 'values': numbers(rows, s['col']),
202
- 'color': resolve_color(c.t, s.get('color'), 'down'),
203
- 'dash': s.get('dash')} for s in series_cfg]
204
- for s in series:
205
- if len(s['values']) != n:
206
- raise ValueError(f"series {s['col']!r} has {len(s['values'])} values but x has {n}")
303
+ many = len(series_cfg) > 1
304
+ series = []
305
+ for index, entry in enumerate(series_cfg):
306
+ col = entry.get('col')
307
+ if col is None:
308
+ raise ValueError('every series entry needs "col"')
309
+ values = numbers(rows, col, allow_none=True)
310
+ if len(values) != n:
311
+ raise ValueError(f"series {col!r} has {len(values)} values but x has {n}")
312
+ chosen = entry.get('color')
313
+ color = (resolve_color(c.t, chosen)
314
+ if chosen is not None else
315
+ (series_color(c.t, index) if many else c.t['down']))
316
+ series.append({'label': entry.get('label', col), 'col': col,
317
+ 'values': values, 'color': color, 'dash': entry.get('dash')})
207
318
 
208
319
  band = cfg.get('band')
209
320
  band_lo = band_hi = None
210
321
  if band:
211
- band_lo, band_hi = numbers(rows, band['lo']), numbers(rows, band['hi'])
322
+ band_lo = numbers(rows, band['lo'], allow_none=True)
323
+ band_hi = numbers(rows, band['hi'], allow_none=True)
212
324
 
213
325
  refs = cfg.get('refs') or []
214
- dom_values = [v for s in series for v in s['values']]
326
+ dom_values = [value for item in series for value in item['values']]
215
327
  if band_lo:
216
328
  dom_values += band_lo + band_hi
217
- dom_values += [float(r['y']) for r in refs if r.get('y') is not None]
218
- y_domain = padded_domain(dom_values, include_zero=cfg.get('include_zero', True))
329
+ ref_values = []
330
+ for ref in refs:
331
+ if ref.get('y') is None:
332
+ continue
333
+ ref_value = float(ref['y'])
334
+ if not math.isfinite(ref_value):
335
+ raise ValueError(f'ref y must be finite, got {ref["y"]!r}')
336
+ ref_values.append(ref_value)
337
+ dom_values += ref_values
338
+ y_domain = padded_domain(dom_values, include_zero=bool(cfg.get('include_zero', False)))
219
339
 
220
340
  ax = Axes(c, rect, xaxis.domain(), y_domain)
221
341
  y_fmt = cfg.get('y_fmt', 'num')
222
- y_dec = cfg.get('y_dec', 0)
223
- formatter = (lambda v: fmt_pct(v, y_dec)) if y_fmt == 'pct' else (lambda v: fmt_num(v, y_dec))
224
- ticks = nice_ticks(y_domain[0], y_domain[1], cfg.get('y_ticks', 5))
225
- ax.grid_y(ticks, [formatter(t) for t in ticks], c.t['line'])
226
-
227
- # 分布带:上下边界围出的多边形
342
+ tick_target = int(cfg.get('y_ticks') or max(2, min(7, round(rect[3] / 60))))
343
+ ticks = nice_ticks(y_domain[0], y_domain[1], tick_target)
344
+ step = min((b - a for a, b in zip(ticks, ticks[1:]) if b > a), default=0)
345
+ step_dec = _decimals_for_step(step)
346
+ dec = max(int(cfg.get('y_dec', 0)), step_dec)
347
+ value_formatter = _formatter(y_fmt, dec)
348
+ tick_formatter = (_formatter('compact', dec) if y_fmt == 'compact'
349
+ else _formatter(y_fmt, step_dec))
350
+ tick_labels = [tick_formatter(t) for t in ticks]
351
+ # 左侧留白放不下完整数字时改用 compact(1,000,000,000 → 10亿)。
352
+ # 宁可换一种数字写法,也不要把轴标签画到画布外——那种图在聊天里看不出错。
353
+ if max((text_width(label, 12.5) for label in tick_labels), default=0) > rect[0] - 8:
354
+ tick_formatter = _formatter('compact', dec)
355
+ value_formatter = tick_formatter
356
+ tick_labels = [tick_formatter(t) for t in ticks]
357
+ ax.grid_y(ticks, tick_labels, c.t['line'])
358
+
359
+ # 分布带:上下边界围出的多边形;缺测处断开,不连成假带。
228
360
  if band:
229
361
  color = resolve_color(c.t, band.get('color'), 'band')
230
- upper = [(ax.px(xaxis.position(i)), ax.py(v)) for i, v in enumerate(band_hi)]
231
- lower = [(ax.px(xaxis.position(i)), ax.py(v)) for i, v in enumerate(reversed(band_lo))]
232
- c.polygon(upper + lower, color, opacity=band.get('opacity', 0.13))
233
- if band.get('label'):
234
- c.text(upper[0][0] + 6, upper[0][1] - 6, band['label'], size=12,
235
- fill=c.t['mute'])
362
+ run = [] # [(px, upper_py, lower_py)],缺测处断开
363
+ first = None
364
+ for i, (upper, lower) in enumerate(zip(band_hi, band_lo)):
365
+ if upper is None or lower is None:
366
+ _flush_band(c, run, color, band.get('opacity', 0.13))
367
+ run = []
368
+ continue
369
+ point = (ax.px(xaxis.position(i)), ax.py(upper), ax.py(lower))
370
+ if first is None:
371
+ first = point
372
+ run.append(point)
373
+ _flush_band(c, run, color, band.get('opacity', 0.13))
374
+ if band.get('label') and first:
375
+ c.text(first[0] + 6, first[1] - 6, band['label'], size=12, fill=c.t['mute'])
236
376
 
237
377
  # 参考线
238
- for ref in refs:
239
- if ref.get('y') is None:
240
- continue
378
+ for ref, ref_value in zip([r for r in refs if r.get('y') is not None], ref_values):
241
379
  color = resolve_color(c.t, ref.get('color'), 'accent')
242
- y = ax.py(float(ref['y']))
380
+ y = ax.py(ref_value)
243
381
  c.line(rect[0], y, rect[0] + rect[2], y, color, ref.get('width', 1.6),
244
382
  dash=ref.get('dash', '6 4'))
245
383
  if ref.get('label'):
246
384
  c.text(rect[0] + 6, y - 7, ref['label'], size=12.5, fill=color)
247
385
 
248
386
  # 折线
249
- for s in series:
250
- pts = [(ax.px(xaxis.position(i)), ax.py(v)) for i, v in enumerate(s['values'])]
387
+ last_label_y = None
388
+ for item in series:
389
+ pts = [None if value is None else (ax.px(xaxis.position(i)), ax.py(value))
390
+ for i, value in enumerate(item['values'])]
391
+ segments = _segments(pts)
251
392
  if cfg.get('area') and len(series) == 1:
252
393
  baseline = ax.py(max(y_domain[0], 0.0))
253
- c.polygon(pts + [(pts[-1][0], baseline), (pts[0][0], baseline)],
254
- s['color'], opacity=0.16)
255
- c.polyline(pts, s['color'], width=s.get('width', 2.6), dash=s['dash'])
256
- # 线尾标系列名
257
- if len(series) > 1 and s.get('label'):
258
- lx, ly = pts[-1]
259
- c.text(lx + 8, ly, s['label'], size=12.5, fill=s['color'], weight='bold',
260
- baseline='middle')
394
+ for segment in segments:
395
+ if len(segment) >= 2:
396
+ c.polygon(segment + [(segment[-1][0], baseline), (segment[0][0], baseline)],
397
+ item['color'], opacity=0.16)
398
+ for segment in segments:
399
+ c.polyline(segment, item['color'], width=item.get('width', 2.6), dash=item.get('dash'))
400
+ # 线尾标系列名(用最后一段的末点,缺测时不会标到画布外)
401
+ if len(series) > 1 and item.get('label') and segments:
402
+ lx, ly = segments[-1][-1]
403
+ # 两条线终点很近时把标签上下错开,避免像 "收盘/MA5" 那样叠在一起
404
+ if last_label_y is not None and abs(ly - last_label_y) < 16:
405
+ ly = last_label_y + (16 if ly >= last_label_y else -16)
406
+ last_label_y = ly
407
+ # 贴近右边界时把系列名放到点的左侧,否则文字会跑出画布
408
+ flip = lx + 8 + text_width(item['label'], 12.5) > rect[0] + rect[2]
409
+ c.text(lx - 8 if flip else lx + 8, ly, item['label'], size=12.5,
410
+ fill=item['color'], weight='bold', baseline='middle',
411
+ anchor='end' if flip else 'start')
261
412
 
262
413
  # 标记点 + 数值
263
414
  if cfg.get('marks'):
@@ -265,18 +416,25 @@ def line(c, rect, cfg, rows):
265
416
  for mark in cfg['marks']:
266
417
  idx = _index_of_mark(xaxis, mark)
267
418
  if idx is None:
419
+ raise ValueError(f'mark {mark!r} is not in the x column {x_col!r}; '
420
+ 'fix the spec instead of dropping the mark silently')
421
+ value = primary['values'][idx]
422
+ if value is None:
268
423
  continue
269
- px, py = ax.px(xaxis.position(idx)), ax.py(primary['values'][idx])
424
+ px, py = ax.px(xaxis.position(idx)), ax.py(value)
270
425
  c.circle(px, py, 4.6, c.t['card'], stroke=primary['color'], stroke_width=2.4)
271
- c.text(px, py - 13, formatter(primary['values'][idx]), size=13,
272
- fill=primary['color'], weight='bold', anchor='middle')
426
+ c.text(px, py - 13, value_formatter(value), size=13, fill=primary['color'],
427
+ weight='bold', anchor='middle')
273
428
 
274
429
  # 文字标注
275
430
  for note in cfg.get('annotate') or []:
276
431
  idx = _index_of_mark(xaxis, note.get('x'))
277
432
  if idx is None:
433
+ raise ValueError(f'annotate x {note.get("x")!r} is not in the x column {x_col!r}')
434
+ value = series[0]['values'][idx]
435
+ if value is None:
278
436
  continue
279
- px, py = ax.px(xaxis.position(idx)), ax.py(series[0]['values'][idx])
437
+ px, py = ax.px(xaxis.position(idx)), ax.py(value)
280
438
  c.text(px + note.get('dx', 8), py + note.get('dy', 0), note.get('text', ''),
281
439
  size=note.get('size', 13), fill=resolve_color(c.t, note.get('color'), 'up'),
282
440
  weight='bold', anchor=note.get('anchor', 'start'))
@@ -321,6 +479,7 @@ def barh(c, rect, cfg, rows):
321
479
  字段:`label`(标签列)、`value`(数值列)、`sign`(可选,带正负的列,
322
480
  决定红/蓝)、`rank`(可选,名次列,画在标签前)、`top`(默认 10)、
323
481
  `fmt`(`compact`/`num`/`pct`)、`dec`(小数位)。
482
+
324
483
  说明文字用 spec 顶层的 `legend`,不在这里——图内元素与页脚说明要由
325
484
  同一个游标排布,图型自己贴底边写说明会和结论行撞在一起。
326
485
  """
@@ -329,31 +488,43 @@ def barh(c, rect, cfg, rows):
329
488
  if label_col is None or value_col is None:
330
489
  raise ValueError('barh chart needs "label" and "value" column names')
331
490
 
332
- pairs = list(zip(labels(rows, label_col), numbers(rows, value_col),
491
+ values = numbers(rows, value_col)
492
+ pairs = list(zip(labels(rows, label_col), values,
333
493
  numbers(rows, cfg['sign']) if cfg.get('sign') else [None] * len(rows),
334
494
  labels(rows, cfg['rank']) if cfg.get('rank') else [None] * len(rows)))
335
495
  if cfg.get('sort', True):
336
496
  pairs.sort(key=lambda p: p[1], reverse=not cfg.get('ascending', False))
337
- pairs = pairs[:int(cfg.get('top', 10))]
497
+ top = int(cfg.get('top', 10))
498
+ pairs = pairs[:top]
338
499
  if not pairs:
339
500
  raise ValueError('barh chart has no rows to draw')
340
501
 
502
+ # 行距至少容得下字号;放不下时先缩字号、再截断并明确写出“显示前 N 条”。
503
+ min_slot = 16.0
504
+ plot_h = rect[3]
505
+ max_rows = max(1, int(plot_h // min_slot))
506
+ note = ''
507
+ if len(pairs) > max_rows:
508
+ note = f'共 {len(pairs)} 条,显示前 {max_rows} 条(提高 height 或调小 top)'
509
+ pairs = pairs[:max_rows]
510
+ plot_h = rect[3] - 20
511
+ rows_n = len(pairs)
512
+ slot = plot_h / rows_n
513
+ font_size = 13.5 if slot >= 20 else max(10.0, min(13.5, slot * 0.68))
514
+ bar_h = max(1.5, min(slot * 0.62, cfg.get('bar_max', 34), slot - 2))
515
+
341
516
  fmt_kind, dec = cfg.get('fmt', 'num'), cfg.get('dec', 0)
342
- if fmt_kind == 'pct':
343
- formatter = lambda v: fmt_pct(v, dec, signed=bool(cfg.get('sign'))) # noqa: E731
344
- elif fmt_kind == 'compact':
345
- formatter = lambda v: fmt_compact(v, dec or 1) # noqa: E731
346
- else:
347
- formatter = lambda v: fmt_num(v, dec) # noqa: E731
517
+ formatter = _formatter(fmt_kind, dec, signed=bool(cfg.get('sign')))
518
+ lo = min(0.0, min(value for _, value, _, _ in pairs))
519
+ hi = max(0.0, max(value for _, value, _, _ in pairs))
520
+ if hi == lo:
521
+ hi = lo + 1.0
348
522
 
349
523
  label_pad = cfg.get('label_width', 168)
350
524
  value_pad = cfg.get('value_width', 104)
351
525
  plot_x = rect[0] + label_pad
352
526
  plot_w = max(rect[2] - label_pad - value_pad, 40)
353
- max_value = max(abs(p[1]) for p in pairs) or 1.0
354
- rows_n = len(pairs)
355
- slot = rect[3] / rows_n
356
- bar_h = min(slot * 0.62, cfg.get('bar_max', 34))
527
+ zero_x = plot_x + (0.0 - lo) / (hi - lo) * plot_w
357
528
 
358
529
  for i, (label, value, sign, rank) in enumerate(pairs):
359
530
  cy = rect[1] + slot * (i + 0.5)
@@ -367,25 +538,34 @@ def barh(c, rect, cfg, rows):
367
538
  else:
368
539
  tone = c.t['neutral']
369
540
 
370
- width = abs(value) / max_value * plot_w
371
- c.rect(plot_x, cy - bar_h / 2, max(width, 1.5), bar_h, tone,
541
+ tip_x = zero_x + value / (hi - lo) * plot_w
542
+ x0, width = min(zero_x, tip_x), max(abs(tip_x - zero_x), 1.5)
543
+ c.rect(x0, cy - bar_h / 2, width, bar_h, tone,
372
544
  rx=min(3, bar_h / 2), opacity=cfg.get('bar_opacity', 0.92))
373
545
 
374
546
  head = f'#{rank} {label}' if rank else label
375
- c.text(rect[0], cy, _ellipsis(head, 13.5, label_pad - 14), size=13.5,
547
+ c.text(rect[0], cy, _ellipsis(head, font_size, label_pad - 14), size=font_size,
376
548
  fill=c.t['ink'], anchor='start', baseline='middle')
377
- c.text(plot_x + width + 8, cy, formatter(value), size=13, fill=tone,
378
- weight='bold', anchor='start', baseline='middle')
549
+ # 数值写在条形外侧:正值在右、负值在左;外侧放不下时写进条形里
550
+ value_text = formatter(value)
551
+ outer_x = tip_x + (8 if tip_x >= zero_x else -8)
552
+ overflow = (tip_x >= zero_x and outer_x + text_width(value_text, font_size)
553
+ > rect[0] + rect[2]) or \
554
+ (tip_x < zero_x and outer_x - text_width(value_text, font_size) < rect[0])
555
+ if overflow and width > text_width(value_text, font_size) + 10:
556
+ c.text(tip_x - (6 if tip_x >= zero_x else -6), cy, value_text, size=font_size,
557
+ fill=contrast_ink(tone, c.t['ink'], c.t['card']), weight='bold',
558
+ anchor='end' if tip_x >= zero_x else 'start', baseline='middle')
559
+ else:
560
+ c.text(outer_x, cy, value_text, size=font_size, fill=tone, weight='bold',
561
+ anchor='start' if tip_x >= zero_x else 'end', baseline='middle')
379
562
 
563
+ # 有负值时画零基线:全负条形从右往左长,没有基线看起来像“全部正增长”。
564
+ if lo < 0:
565
+ c.line(zero_x, rect[1], zero_x, rect[1] + plot_h, c.t['line'], 1)
380
566
 
381
- def _ellipsis(text, size, max_width):
382
- """按估算宽度截断并加省略号,避免长标签压到条形上。"""
383
- if text_width(text, size) <= max_width:
384
- return text
385
- cut = text
386
- while cut and text_width(cut + '…', size) > max_width:
387
- cut = cut[:-1]
388
- return cut + '…'
567
+ if note:
568
+ c.text(rect[0], rect[1] + rect[3] - 2, note, size=11, fill=c.t['mute'])
389
569
 
390
570
 
391
571
  # ---------------------------------------------------------------- table
@@ -394,61 +574,589 @@ def _ellipsis(text, size, max_width):
394
574
  def table(c, rect, cfg, rows):
395
575
  """表格,用于名录类数据(基金列表、成分股、接口字段)。
396
576
 
397
- 字段:`columns`(必填,`[{col,label,align,dec}]`)、`top`(默认 12)、
577
+ 字段:`columns`(必填,`[{col,label,align,dec,weight}]`)、`top`(默认 12)、
398
578
  `row_height`(默认 30)、`font_size`(默认 13)。
579
+ 列可写 `"type": "sparkline"`,该列的值必须是数字数组,表格里画迷你走势线。
580
+
581
+ 行数放不下时按可用高度截断,并在表底写明“共 N 条,显示前 k 条”,
582
+ 不让表格盖到 legend/结论行上。
399
583
  """
400
584
  columns = cfg.get('columns') or []
401
585
  if not columns:
402
586
  raise ValueError('table chart needs "columns": [{col, label}]')
403
587
  limit = int(cfg.get('top', 12))
404
- shown = rows[:limit]
405
588
  size = cfg.get('font_size', 13)
406
- row_h = cfg.get('row_height', 30)
589
+ row_h = float(cfg.get('row_height', 30))
590
+ min_row_h = size + 8
591
+
592
+ wanted = min(limit, len(rows))
593
+ if wanted <= 0:
594
+ raise ValueError('table chart needs at least one row')
595
+ header_h = size + row_h * 0.55 + 6
596
+ avail = rect[3] - header_h
597
+ note_h = 18 if wanted < len(rows) else 0
598
+ if row_h * wanted > avail - note_h:
599
+ row_h = max(min_row_h, (avail - note_h) / wanted)
600
+ fit = max(1, int((avail - note_h) // row_h))
601
+ if fit < wanted and note_h == 0:
602
+ # 实际是被高度截断的:补一条“显示前 N 条”的位置再重算
603
+ note_h = 18
604
+ row_h = max(min_row_h, (avail - note_h) / wanted)
605
+ fit = max(1, int((avail - note_h) // row_h))
606
+ shown = min(wanted, fit)
607
+ truncated = shown < len(rows)
608
+ shown_rows = rows[:shown]
407
609
 
408
610
  weights = [col.get('weight', 1) for col in columns]
409
611
  total = sum(weights) or 1
410
612
  widths = [rect[2] * w / total for w in weights]
411
613
  offsets, acc = [], rect[0]
412
- for w in widths:
614
+ for width in widths:
413
615
  offsets.append(acc)
414
- acc += w
616
+ acc += width
415
617
 
416
618
  # 表头
417
619
  y = rect[1] + size
418
- for col, x, w in zip(columns, offsets, widths):
620
+ for col, x, width in zip(columns, offsets, widths):
419
621
  align = col.get('align', 'left')
420
- tx = x if align == 'left' else x + w - 6
622
+ tx = x if align == 'left' else x + width - 6
421
623
  c.text(tx, y, col.get('label', col['col']), size=size, fill=c.t['mute'],
422
624
  weight='bold', anchor='start' if align == 'left' else 'end')
423
625
  y += row_h * 0.55
424
626
  c.line(rect[0], y, rect[0] + rect[2], y, c.t['line'], 1)
425
627
 
426
628
  # 数据行
427
- for r, row in enumerate(shown):
629
+ for r, row in enumerate(shown_rows):
428
630
  y += row_h
429
631
  if r % 2 == 1:
430
632
  c.rect(rect[0], y - size - 6, rect[2], row_h - 4, c.t['card'], opacity=0.7)
431
- for col, x, w in zip(columns, offsets, widths):
432
- raw = row.get(col['col'])
433
- text = _cell_text(raw, col)
633
+ for col, x, width in zip(columns, offsets, widths):
434
634
  align = col.get('align', 'left')
435
- tx = x if align == 'left' else x + w - 6
436
- c.text(tx, y, _ellipsis(text, size, w - 12), size=size, fill=c.t['ink'],
635
+ tx = x if align == 'left' else x + width - 6
636
+ if col.get('type') == 'sparkline':
637
+ _table_sparkline(c, row, col, x + 4, y - size + 2, width - 12,
638
+ max(8.0, row_h - 12))
639
+ continue
640
+ if col['col'] not in row:
641
+ raise KeyError(f'table column {col["col"]!r} missing at row {r}; '
642
+ + 'available: ' + ', '.join(sorted(row)))
643
+ text = _cell_text(row.get(col['col']), col)
644
+ c.text(tx, y, _ellipsis(text, size, width - 12), size=size, fill=c.t['ink'],
437
645
  anchor='start' if align == 'left' else 'end')
438
646
 
439
- if len(rows) > limit:
440
- c.text(rect[0], y + row_h * 0.9, f'(共 {len(rows)} 条,此处显示前 {limit} 条)',
441
- size=12, fill=c.t['mute'])
647
+ if truncated:
648
+ c.text(rect[0], rect[1] + rect[3] - 2,
649
+ f'共 {len(rows)} 条,显示前 {shown} 条', size=11, fill=c.t['mute'])
650
+
651
+
652
+ def _table_sparkline(c, row, col, x, y, width, height):
653
+ """表格里的迷你走势:一条折线,按首尾方向取涨/跌色。"""
654
+ raw = row.get(col['col'])
655
+ if not isinstance(raw, (list, tuple)):
656
+ raise TypeError(f'table.sparkline column {col["col"]!r} must be an array of numbers')
657
+ values = []
658
+ for value in raw:
659
+ if isinstance(value, bool) or value is None:
660
+ continue
661
+ try:
662
+ number = float(value)
663
+ except (TypeError, ValueError):
664
+ continue
665
+ if math.isfinite(number):
666
+ values.append(number)
667
+ if len(values) < 2:
668
+ return
669
+ lo, hi = min(values), max(values)
670
+ span = hi - lo or 1.0
671
+ points = [(x + index / (len(values) - 1) * width,
672
+ y + height - (value - lo) / span * height) for index, value in enumerate(values)]
673
+ tone = c.t['up'] if values[-1] >= values[0] else c.t['down']
674
+ c.polyline(points, tone, width=1.4)
442
675
 
443
676
 
444
677
  def _cell_text(raw, col):
445
- """单元格取值:按 `dec` 格式化数值,缺失写 `—`(不写 None)。"""
678
+ """单元格取值:按 `fmt`/`dec` 格式化数值,缺失写 `—`(不写 None)。"""
446
679
  if raw is None:
447
680
  return '—'
681
+ fmt_kind = col.get('fmt')
448
682
  dec = col.get('dec')
449
- if dec is not None:
450
- try:
451
- return fmt_num(float(raw), int(dec))
452
- except (TypeError, ValueError):
453
- return str(raw)
454
- return str(raw)
683
+ if fmt_kind is None and dec is None:
684
+ return str(raw)
685
+ try:
686
+ number = float(raw)
687
+ except (TypeError, ValueError):
688
+ return str(raw)
689
+ if fmt_kind is None:
690
+ fmt_kind = 'num'
691
+ return _formatter(fmt_kind, int(dec) if dec is not None else 0)(number)
692
+
693
+
694
+ # ---------------------------------------------------------------- heatmap
695
+
696
+ @chart('heatmap', x_axis=True, x_axis_height=36)
697
+ def heatmap(c, rect, cfg, rows):
698
+ """矩阵热力图:横截面 × 时间(或板块 × 指标)的数值强度。
699
+
700
+ 字段:`x`(列标签列)、`y`(行标签列)、`value`(数值列)、
701
+ `fmt`(`num`/`pct`/`compact`)、`dec`、`diverging`(默认按数据正负自动判断)、
702
+ `show_value`(格子里写数值,默认 false)、`label_width`(默认按行标签实测宽度)、
703
+ `top`(最多显示多少行,默认全部;放不下会报错要求调大 height)。
704
+ """
705
+ for key in ('x', 'y', 'value'):
706
+ if not cfg.get(key):
707
+ raise ValueError(f'heatmap chart needs "{key}" column name')
708
+ xs = labels(rows, cfg['x'])
709
+ ys = labels(rows, cfg['y'])
710
+ values = numbers(rows, cfg['value'])
711
+ x_order = list(dict.fromkeys(xs))
712
+ y_order = list(dict.fromkeys(ys))
713
+ cell = {}
714
+ for row_x, row_y, value in zip(xs, ys, values):
715
+ cell[(row_y, row_x)] = value
716
+
717
+ limit = cfg.get('top')
718
+ if limit is not None:
719
+ y_order = y_order[:int(limit)]
720
+ row_min = 13.0
721
+ max_rows = max(1, int(rect[3] // row_min))
722
+ if len(y_order) > max_rows:
723
+ raise ValueError(
724
+ f'heatmap has {len(y_order)} rows but only {max_rows} fit at this height; '
725
+ 'raise spec height, lower "top", or use a table')
726
+
727
+ label_size = 12.0
728
+ label_width = cfg.get('label_width')
729
+ if label_width is None:
730
+ label_width = min(max([text_width(label, label_size) for label in y_order] + [0]) + 14,
731
+ rect[2] * 0.34)
732
+ label_width = max(label_width, 32)
733
+ plot_x = rect[0] + label_width
734
+ plot_w = rect[2] - label_width
735
+ plot_h = rect[3] - 22
736
+ cell_w = plot_w / len(x_order)
737
+ cell_h = plot_h / len(y_order)
738
+ gap = float(cfg.get('cell_gap', 1.5))
739
+
740
+ flat = [value for key, value in cell.items() if key[0] in set(y_order)]
741
+ lo, hi = min(flat), max(flat)
742
+ diverging = cfg.get('diverging')
743
+ if diverging is None:
744
+ diverging = lo < 0 < hi
745
+ max_abs = max(abs(lo), abs(hi), 1e-12)
746
+ base = c.t['card']
747
+ positive = c.t['up'] if diverging else (c.t.get('band') or c.t['down'])
748
+ negative = c.t['down']
749
+
750
+ # 列标签抽稀:按可用宽度选位置,首尾必显。
751
+ label_step = max(1, int(math.ceil(44 / max(cell_w, 1))))
752
+ x_label_indices = set(range(0, len(x_order), label_step))
753
+ x_label_indices.add(len(x_order) - 1)
754
+
755
+ for row_index, row_label in enumerate(y_order):
756
+ top = rect[1] + row_index * cell_h
757
+ for col_index, col_label in enumerate(x_order):
758
+ value = cell.get((row_label, col_label))
759
+ if value is None:
760
+ continue
761
+ if diverging:
762
+ strength = 0.06 + 0.82 * (abs(value) / max_abs) ** 0.7
763
+ color = positive if value >= 0 else negative
764
+ else:
765
+ ratio = (value - lo) / (hi - lo) if hi > lo else 0.5
766
+ strength = 0.06 + 0.82 * ratio
767
+ color = positive
768
+ fill = mix_hex(base, color, strength)
769
+ left = plot_x + col_index * cell_w
770
+ c.rect(left + gap / 2, top + gap / 2, max(cell_w - gap, 0.5),
771
+ max(cell_h - gap, 0.5), fill, rx=2)
772
+ if cfg.get('show_value') and cell_w > 34 and cell_h > 14:
773
+ c.text(left + cell_w / 2, top + cell_h / 2,
774
+ _formatter(cfg.get('fmt', 'num'), cfg.get('dec', 0))(value),
775
+ size=min(11.0, cell_h * 0.55), anchor='middle', baseline='middle',
776
+ fill=contrast_ink(fill, c.t['ink'], c.t['card']))
777
+ c.text(plot_x - 8, rect[1] + row_index * cell_h + cell_h / 2,
778
+ _ellipsis(row_label, label_size, label_width - 12),
779
+ size=label_size, fill=c.t['ink'], anchor='end', baseline='middle')
780
+
781
+ compact_dates = not has_multiple_years(x_order)
782
+ for col_index in sorted(x_label_indices):
783
+ label = fmt_date_label(x_order[col_index], compact=compact_dates)
784
+ c.text(plot_x + col_index * cell_w + cell_w / 2, rect[1] + plot_h + 17,
785
+ _ellipsis(label, 11.5, max(cell_w * label_step - 4, 28)),
786
+ size=11.5, fill=c.t['mute'], anchor='middle')
787
+
788
+
789
+ # ---------------------------------------------------------------- treemap
790
+
791
+ @chart('treemap')
792
+ def treemap(c, rect, cfg, rows):
793
+ """矩形树图:市值/权重构成、板块内个股占比。
794
+
795
+ 字段:`label`、`value`(必须为正数)、`group`(可选,按分组着色)、
796
+ `fmt`、`dec`、`top`(默认全部)。
797
+ 面积算法为二分切分(squarified 的简化版),块内写名称与数值,
798
+ 标题/口径说明放进 spec 的 `legend` 与 `notes`。
799
+ """
800
+ label_col = cfg.get('label')
801
+ value_col = cfg.get('value')
802
+ if label_col is None or value_col is None:
803
+ raise ValueError('treemap chart needs "label" and "value" column names')
804
+ groups = labels(rows, cfg['group']) if cfg.get('group') else [''] * len(rows)
805
+ items = list(zip(labels(rows, label_col), numbers(rows, value_col), groups))
806
+ for index, (_, value, _) in enumerate(items):
807
+ if value <= 0:
808
+ raise ValueError(f'treemap needs positive values, row {index} is {value!r}')
809
+ items.sort(key=lambda item: item[1], reverse=True)
810
+ if cfg.get('top') is not None:
811
+ items = items[:int(cfg['top'])]
812
+
813
+ if not items:
814
+ raise ValueError('treemap chart has no rows to draw')
815
+ group_order = list(dict.fromkeys(group for _, _, group in items))
816
+ palette = {group: (series_color(c.t, i) if len(group_order) > 1 else c.t.get('band', c.t['down']))
817
+ for i, group in enumerate(group_order)}
818
+ formatter = _formatter(cfg.get('fmt', 'compact'), cfg.get('dec', 1))
819
+
820
+ for left, top, width, height, (label, value, group) in _treemap_rects(items, rect):
821
+ tone = palette[group]
822
+ fill = mix_hex(c.t['card'], tone, 0.20)
823
+ c.rect(left + 1, top + 1, max(width - 2, 1), max(height - 2, 1), fill,
824
+ rx=3, stroke=tone, stroke_width=1)
825
+ if width < 52 or height < 20:
826
+ continue
827
+ name = _ellipsis(label, 12.0, width - 12)
828
+ c.text(left + 7, top + 17, name, size=12, fill=c.t['ink'], weight='bold')
829
+ if height >= 36:
830
+ c.text(left + 7, top + 33, formatter(value), size=11,
831
+ fill=c.t['mute'])
832
+
833
+
834
+ def _treemap_rects(items, rect):
835
+ """把 `(label, value, group)` 列表铺满矩形,返回 `(x, y, w, h, item)`。
836
+
837
+ 二分切分:每次按面积总和的一半把序列分成两组,沿较长边按比例切开。
838
+ 块的长宽比不如严格 squarified 均匀,但无递归内层排序、结果稳定,
839
+ 对 10–40 个标的的构成图足够。
840
+ """
841
+ out = []
842
+
843
+ def split(subset, x, y, width, height):
844
+ if not subset:
845
+ return
846
+ if len(subset) == 1:
847
+ out.append((x, y, width, height, subset[0]))
848
+ return
849
+ total = sum(item[1] for item in subset)
850
+ half = total / 2
851
+ acc, cut = 0.0, 1
852
+ for index in range(len(subset) - 1):
853
+ acc += subset[index][1]
854
+ cut = index + 1
855
+ if acc >= half:
856
+ break
857
+ left, right = subset[:cut], subset[cut:]
858
+ left_value = sum(item[1] for item in left)
859
+ ratio = (left_value / total) if total > 0 else 0.5
860
+ if width >= height:
861
+ split(left, x, y, width * ratio, height)
862
+ split(right, x + width * ratio, y, width * (1 - ratio), height)
863
+ else:
864
+ split(left, x, y, width, height * ratio)
865
+ split(right, x, y + height * ratio, width, height * (1 - ratio))
866
+
867
+ split(items, rect[0], rect[1], rect[2], rect[3])
868
+ return out
869
+
870
+
871
+ # ---------------------------------------------------------------- waterfall
872
+
873
+ @chart('waterfall', x_axis=True)
874
+ def waterfall(c, rect, cfg, rows):
875
+ """瀑布图:资金流、营收/利润的逐项拆解。
876
+
877
+ 字段:`label`、`value`(增量列)、`fmt`、`dec`、`type_col`(可选,默认 `type`;
878
+ 该列值为 `total` 的行表示汇总,从 0 起画整根)、`sort`(默认 false)。
879
+ 每个增量从前一根的终点起画,正增量红、负增量蓝。
880
+ """
881
+ label_col = cfg.get('label')
882
+ value_col = cfg.get('value')
883
+ if label_col is None or value_col is None:
884
+ raise ValueError('waterfall chart needs "label" and "value" column names')
885
+ labels_list = labels(rows, label_col)
886
+ values = numbers(rows, value_col)
887
+ type_col = cfg.get('type_col', 'type')
888
+ totals = [str(row.get(type_col, '')).strip().lower() in ('total', 'sum', '合计', '汇总')
889
+ for row in rows]
890
+ if cfg.get('sort', False):
891
+ order = sorted(range(len(values)), key=lambda i: values[i], reverse=True)
892
+ labels_list = [labels_list[i] for i in order]
893
+ values = [values[i] for i in order]
894
+ totals = [totals[i] for i in order]
895
+ if not values:
896
+ raise ValueError('waterfall chart has no rows to draw')
897
+
898
+ starts, ends, cursor = [], [], 0.0
899
+ for value, is_total in zip(values, totals):
900
+ if is_total:
901
+ starts.append(0.0)
902
+ ends.append(value)
903
+ cursor = value
904
+ else:
905
+ starts.append(cursor)
906
+ ends.append(cursor + value)
907
+ cursor += value
908
+
909
+ lo = min(min(starts), min(ends), 0.0)
910
+ hi = max(max(starts), max(ends), 0.0)
911
+ y_domain = padded_domain([lo, hi], include_zero=True, pad=0.06)
912
+ ax = Axes(c, rect, (0, len(values)), y_domain)
913
+ tick_target = int(cfg.get('y_ticks') or max(2, min(7, round(rect[3] / 60))))
914
+ ticks = nice_ticks(y_domain[0], y_domain[1], tick_target)
915
+ step = min((b - a for a, b in zip(ticks, ticks[1:]) if b > a), default=0)
916
+ dec = max(int(cfg.get('dec', 0)), _decimals_for_step(step))
917
+ formatter = _formatter(cfg.get('fmt', 'compact'), dec, signed=True)
918
+ tick_formatter = _formatter(cfg.get('fmt', 'compact'), _decimals_for_step(step))
919
+ ax.grid_y(ticks, [tick_formatter(t) for t in ticks], c.t['line'])
920
+ zero_y = ax.py(0.0)
921
+ c.line(rect[0], zero_y, rect[0] + rect[2], zero_y, c.t['line'], 1.5)
922
+
923
+ slot = rect[2] / len(values)
924
+ bar_w = max(2.0, min(slot * 0.56, 46))
925
+ label_size = 11.5
926
+ for index, (label, start, end) in enumerate(zip(labels_list, starts, ends)):
927
+ cx = rect[0] + slot * (index + 0.5)
928
+ top, bottom = ax.py(max(start, end)), ax.py(min(start, end))
929
+ tone = c.t['up'] if end >= start else c.t['down']
930
+ c.rect(cx - bar_w / 2, top, bar_w, max(bottom - top, 1.0), tone, rx=2,
931
+ opacity=cfg.get('bar_opacity', 0.9))
932
+ value_text = formatter(end - start if not totals[index] else end)
933
+ c.text(cx, max(top - 6, rect[1] + 10), value_text, size=10.5, fill=tone,
934
+ weight='bold', anchor='middle')
935
+ if index > 0:
936
+ # 连接线:从前一根终点拉到这一根的起点,读图时知道累计关系
937
+ c.line(rect[0] + slot * (index - 0.5) + bar_w / 2, ax.py(ends[index - 1]),
938
+ rect[0] + slot * (index + 0.5) - bar_w / 2, ax.py(starts[index]),
939
+ c.t['line'], 1, dash='4 4')
940
+ c.text(cx, rect[1] + rect[3] + 21, _ellipsis(label, label_size, max(slot - 4, 24)),
941
+ size=label_size, fill=c.t['mute'], anchor='middle')
942
+
943
+
944
+ # ---------------------------------------------------------------- timeline
945
+
946
+ @chart('timeline', x_axis=True, x_axis_height=30)
947
+ def timeline(c, rect, cfg, rows):
948
+ """事件时间轴:公告、政策、除权、事件驱动的时间分布。
949
+
950
+ 字段:`x`(日期列)、`label`(事件名)、`sign`(可选,正负决定颜色)、
951
+ `detail`(可选,事件说明小字)、`color`(无 sign 时的事件色)。
952
+ 事件按日期排序(日期无法全部解析时保留行序),横向等距摆放;标签最多
953
+ 三层交错,放不下的会省略并在图内注明数量。
954
+ """
955
+ x_col = cfg.get('x')
956
+ label_col = cfg.get('label')
957
+ if x_col is None or label_col is None:
958
+ raise ValueError('timeline chart needs "x" and "label" column names')
959
+ raw_dates = labels(rows, x_col)
960
+ events = labels(rows, label_col)
961
+ detail_col = cfg.get('detail')
962
+ details = labels(rows, detail_col) if detail_col else [None] * len(rows)
963
+ signs = numbers(rows, cfg['sign']) if cfg.get('sign') else [None] * len(rows)
964
+
965
+ parts = [date_parts(value) for value in raw_dates]
966
+ order = list(range(len(rows)))
967
+ if parts and all(part is not None for part in parts):
968
+ order.sort(key=lambda index: (parts[index][0], parts[index][1],
969
+ parts[index][2] if parts[index][2] is not None else 0))
970
+
971
+ n = len(order)
972
+ pad = 26.0
973
+ left = rect[0] + pad
974
+ right = rect[0] + rect[2] - pad
975
+ line_y = rect[1] + rect[3] * 0.54
976
+ step = (right - left) / (n - 1) if n > 1 else 0.0
977
+ c.line(left - 6, line_y, right + 6, line_y, c.t['line'], 1.5)
978
+
979
+ max_levels = min(3, max(1, int((line_y - rect[1] - 24) // 40)))
980
+ occupied = [[] for _ in range(max_levels)]
981
+ omitted = 0
982
+ default_tone = resolve_color(c.t, cfg.get('color'), 'accent')
983
+ label_size = 12.5
984
+ for rank, index in enumerate(order):
985
+ px = (left + right) / 2 if n == 1 else left + step * rank
986
+ sign = signs[index]
987
+ if sign is None:
988
+ tone = default_tone
989
+ elif sign > 0:
990
+ tone = c.t['up']
991
+ elif sign < 0:
992
+ tone = c.t['down']
993
+ else:
994
+ tone = c.t['neutral']
995
+ c.circle(px, line_y, 4.6, c.t['card'], stroke=tone, stroke_width=2.2)
996
+
997
+ label = _ellipsis(events[index], label_size, 190)
998
+ detail = details[index]
999
+ width = max(text_width(label, label_size),
1000
+ text_width(detail, 11) if detail else 0) + 10
1001
+ level = None
1002
+ for candidate in range(max_levels):
1003
+ if all(px + width / 2 < start or px - width / 2 > end + 6
1004
+ for start, end in occupied[candidate]):
1005
+ occupied[candidate].append((px - width / 2, px + width / 2))
1006
+ level = candidate
1007
+ break
1008
+ if level is None:
1009
+ omitted += 1
1010
+ continue
1011
+ label_y = line_y - 24 - level * 40
1012
+ c.line(px, line_y - 6, px, label_y + 5, c.t['line'], 1, dash='3 3')
1013
+ c.text(px, label_y, label, size=label_size, fill=tone, weight='bold', anchor='middle')
1014
+ if detail:
1015
+ c.text(px, label_y + 16, _ellipsis(detail, 11, 190), size=11,
1016
+ fill=c.t['mute'], anchor='middle')
1017
+
1018
+ compact_dates = not has_multiple_years(raw_dates)
1019
+ capacity = max(2, int(rect[2] // 64))
1020
+ stride = max(1, math.ceil(n / capacity))
1021
+ for rank, index in enumerate(order):
1022
+ if rank % stride and rank != n - 1:
1023
+ continue
1024
+ px = (left + right) / 2 if n == 1 else left + step * rank
1025
+ c.text(px, rect[1] + rect[3] + 18,
1026
+ fmt_date_label(raw_dates[index], compact=compact_dates),
1027
+ size=11.5, fill=c.t['mute'], anchor='middle')
1028
+
1029
+ if omitted:
1030
+ c.text(rect[0] + rect[2], rect[1] + 12, f'{omitted} 个标签过密未显示',
1031
+ size=10.5, fill=c.t['mute'], anchor='end')
1032
+
1033
+
1034
+ # ---------------------------------------------------------------- chain
1035
+
1036
+ @chart('chain', needs_rows=False)
1037
+ def chain(c, rect, cfg, rows):
1038
+ """产业链/传导链示意图:声明式分层节点 + 有向边。
1039
+
1040
+ spec:
1041
+ `layers` [{name?, nodes:[节点名...]}, ...],层从左到右;
1042
+ `edges` [[上游节点, 下游节点], ...],有向边只能从靠前的层指向靠后的层;
1043
+ `highlight` 可选,高亮的节点名列表。
1044
+ 节点名同时是边的引用 id;节点宽高按文本测量,层距/行距自适应;
1045
+ 放不下会缩小字号,再放不下直接报错,不画出互相压字的图。
1046
+ """
1047
+ layers = cfg.get('layers')
1048
+ if not isinstance(layers, list) or not layers:
1049
+ raise ValueError('chain chart needs "layers": [{name, nodes: [label...]}, ...]')
1050
+ normalized = []
1051
+ seen = {}
1052
+ for layer_index, layer in enumerate(layers):
1053
+ if not isinstance(layer, dict) or not isinstance(layer.get('nodes'), list):
1054
+ raise ValueError(f'chain.layers[{layer_index}] must be an object with a "nodes" array')
1055
+ names = []
1056
+ for node in layer['nodes']:
1057
+ label = str(node).strip()
1058
+ if not label:
1059
+ raise ValueError(f'chain.layers[{layer_index}] has an empty node label')
1060
+ if label in seen:
1061
+ raise ValueError(f'chain node {label!r} appears twice; node labels are ids')
1062
+ seen[label] = layer_index
1063
+ names.append(label)
1064
+ if not names:
1065
+ raise ValueError(f'chain.layers[{layer_index}] has no nodes')
1066
+ normalized.append({'name': str(layer.get('name') or ''), 'nodes': names})
1067
+
1068
+ highlight = [str(name) for name in (cfg.get('highlight') or [])]
1069
+ for name in highlight:
1070
+ if name not in seen:
1071
+ raise ValueError(f'chain.highlight names unknown node {name!r}')
1072
+
1073
+ edges = []
1074
+ for raw in cfg.get('edges') or []:
1075
+ if not isinstance(raw, (list, tuple)) or len(raw) != 2:
1076
+ raise ValueError('chain edge must be [from, to]')
1077
+ source, target = str(raw[0]), str(raw[1])
1078
+ if source not in seen or target not in seen:
1079
+ raise ValueError(f'chain edge {source!r} -> {target!r} names an unknown node')
1080
+ if seen[target] < seen[source]:
1081
+ raise ValueError(f'chain edge {source!r} -> {target!r} cannot go backwards '
1082
+ '(target layer is earlier than source layer)')
1083
+ edges.append((source, target))
1084
+
1085
+ # 尝试逐级缩小字号/内边距,直到放得下
1086
+ layout = None
1087
+ for size, pad_x, height in ((12.5, 26, 34), (11.5, 22, 30), (10.5, 18, 27), (10.0, 16, 25)):
1088
+ widths = [max(max(text_width(name, size) for name in layer['nodes']) + pad_x, 64)
1089
+ for layer in normalized]
1090
+ gap = 56 if size >= 12 else 36
1091
+ total_width = sum(widths) + gap * (len(normalized) - 1)
1092
+ vgap = 16 if size >= 12 else 10
1093
+ stack_height = max(len(layer['nodes']) * height + (len(layer['nodes']) - 1) * vgap
1094
+ for layer in normalized)
1095
+ caption_h = 20
1096
+ if total_width <= rect[2] and stack_height + caption_h <= rect[3]:
1097
+ layout = (size, pad_x, height, gap, vgap, widths, stack_height)
1098
+ break
1099
+ if layout is None:
1100
+ raise ValueError('chain does not fit: reduce layers/nodes or labels, or raise the canvas size')
1101
+ size, pad_x, height, gap, vgap, widths, stack_height = layout
1102
+
1103
+ c.raw(_arrow_marker('chain-arrow', c.t['mute']))
1104
+ positions = {}
1105
+ # 图整体水平居中:链短时不会贴左,链长时才铺满
1106
+ total_width = sum(widths) + gap * (len(normalized) - 1)
1107
+ cursor_x = rect[0] + max((rect[2] - total_width) / 2, 0)
1108
+ stack_top = rect[1] + (rect[3] - stack_height) / 2
1109
+ for layer_index, layer in enumerate(normalized):
1110
+ width = widths[layer_index]
1111
+ count = len(layer['nodes'])
1112
+ block_h = count * height + (count - 1) * vgap
1113
+ top = rect[1] + (rect[3] - block_h) / 2
1114
+ for node_index, name in enumerate(layer['nodes']):
1115
+ node_y = top + node_index * (height + vgap)
1116
+ positions[name] = (cursor_x, node_y, width, height, layer_index)
1117
+ if layer['name']:
1118
+ c.text(cursor_x + width / 2, stack_top - 8, layer['name'],
1119
+ size=11.5, fill=c.t['mute'], weight='bold', anchor='middle')
1120
+ cursor_x += width + gap
1121
+
1122
+ # 先画边(在节点下面),再画节点
1123
+ for source, target in edges:
1124
+ sx, sy, sw, sh, source_layer = positions[source]
1125
+ tx, ty, tw, th, target_layer = positions[target]
1126
+ if source_layer == target_layer:
1127
+ # 同层内的传导:按上下关系画竖箭头,不绕到画布外
1128
+ if ty > sy:
1129
+ start, end = (sx + sw / 2, sy + sh), (tx + tw / 2, ty)
1130
+ else:
1131
+ start, end = (sx + sw / 2, sy), (tx + tw / 2, ty + th)
1132
+ path = f'M {start[0]:.2f} {start[1]:.2f} L {end[0]:.2f} {end[1]:.2f}'
1133
+ else:
1134
+ start = (sx + sw, sy + sh / 2)
1135
+ end = (tx, ty + th / 2)
1136
+ span = max(end[0] - start[0], 1.0)
1137
+ control = span * 0.45
1138
+ path = (f'M {start[0]:.2f} {start[1]:.2f} '
1139
+ f'C {start[0] + control:.2f} {start[1]:.2f} '
1140
+ f'{end[0] - control:.2f} {end[1]:.2f} {end[0]:.2f} {end[1]:.2f}')
1141
+ c.path(path, stroke=c.t['mute'], width=1.4, marker_end='chain-arrow')
1142
+
1143
+ for name, (x, y, width, node_height, layer_index) in positions.items():
1144
+ tone = series_color(c.t, layer_index)
1145
+ if name in highlight:
1146
+ fill = mix_hex(c.t['card'], c.t['accent'], 0.24)
1147
+ stroke, stroke_width = c.t['accent'], 2.0
1148
+ else:
1149
+ fill = mix_hex(c.t['card'], tone, 0.16)
1150
+ stroke, stroke_width = tone, 1.2
1151
+ c.rect(x, y, width, node_height, fill, rx=9, stroke=stroke, stroke_width=stroke_width)
1152
+ c.text(x + width / 2, y + node_height / 2, _ellipsis(name, size, width - 14),
1153
+ size=size, fill=c.t['ink'], weight='bold', anchor='middle', baseline='middle')
1154
+
1155
+
1156
+ def _arrow_marker(marker_id, color):
1157
+ """有向边用的箭头定义;用 userSpaceOnUse 保证不同线宽下箭头大小一致。"""
1158
+ return (f'<defs><marker id="{marker_id}" viewBox="0 0 10 10" refX="8" refY="5" '
1159
+ f'markerWidth="10" markerHeight="10" markerUnits="userSpaceOnUse" '
1160
+ f'orient="auto-start-reverse"><path d="M 1 1.5 L 8.5 5 L 1 8.5" fill="none" '
1161
+ f'stroke="{color}" stroke-width="1.6" stroke-linecap="round" '
1162
+ f'stroke-linejoin="round"/></marker></defs>')