@dsh-ft/dsh-fft-plot 0.0.0-stage → 0.1.1

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.
package/README.md CHANGED
@@ -1,3 +1,67 @@
1
- # Temporary Holding Version
1
+ # @dsh-ft/dsh-fft-plot
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ FTShare 数据出图。随包分发一个 skill `dsh-fft-plot`:把 FTShare 接口返回的数据渲染成
4
+ SVG,图直接内联在对话里显示。
5
+
6
+ ## 形态
7
+
8
+ 大幅改动一般不需要。要换数据字段只改 spec;要加图型只改 `charts.py`。
9
+
10
+ ```
11
+ dsh-fft-plot/
12
+ ├── src/index.js skill provider(纯 JS,无构建)
13
+ ├── cordis.patch.yml 一行 insert
14
+ └── skills/dsh-fft-plot/
15
+ ├── SKILL.md 给模型看:何时画、画哪种、字段怎么填
16
+ └── scripts/
17
+ ├── plot.py CLI:spec(JSON) → SVG
18
+ └── ftplot/
19
+ ├── theme.py 配色主题(键名固定)
20
+ ├── canvas.py SVG 画布、坐标系、日期/数值格式
21
+ ├── charts.py 图型注册表 @chart('名字')
22
+ └── spec.py spec 与数据加载
23
+ ```
24
+
25
+ ## 为什么不用 matplotlib
26
+
27
+ matplotlib 约 200MB,而 DSH 自带 Python 里没有它,装一个 skill 要拉这么大一坨不划算。
28
+ 这里手写 SVG,只用标准库:
29
+
30
+ | | matplotlib | 本包 |
31
+ | --- | --- | --- |
32
+ | 依赖 | ~200MB | 0 |
33
+ | 单图体积 | 58KB | 3–20KB |
34
+ | 文字 | 转成路径,不可搜索 | 真 `<text>`,可选中可搜索 |
35
+
36
+ 代价是图元要自己维护(`canvas.py` 283 行 + `charts.py` 454 行),换来零依赖与样式完全可控。
37
+
38
+ ## 加一种图
39
+
40
+ `charts.py` 里写一个函数加装饰器即可:
41
+
42
+ ```python
43
+ @chart('curve')
44
+ def curve(c, rect, cfg, rows):
45
+ """期限结构曲线。字段:x, series"""
46
+ ...
47
+ ```
48
+
49
+ 签名固定 `(c, rect, cfg, rows)`;颜色一律走 `resolve_color(c.t, ...)`,不写死。
50
+ 然后在 `SKILL.md` 的图型表补一行字段说明——那是模型选图的依据。
51
+
52
+ **不需要**改 `plot.py` 或任何布局代码。
53
+
54
+ ## 本地验证
55
+
56
+ ```bash
57
+ python3 skills/dsh-fft-plot/scripts/plot.py --spec spec.json --out /abs/chart.svg
58
+ ```
59
+
60
+ 产物是自包含 SVG(浅色底、无外链、无脚本),可直接写进 Markdown 图片语法。
61
+
62
+ ## 两条设计约束
63
+
64
+ - **浅色底不透明**:SVG 作为 `<img>` 内联时是独立文档,读不到宿主的
65
+ `body[data-ds-dark-theme]`,深色模式下只有自带底色才不会黑底黑字。
66
+ - **布局单游标**:头部、绘图区、说明、结论、页脚全部由 `plot.py` 一个游标顺序排,
67
+ 图型不得自己贴底边写字——那样必然和结论行重叠(已踩过)。
@@ -0,0 +1,14 @@
1
+ # dsh-fft-plot bundle patch
2
+ #
3
+ # `dsh.bundle.patch` layer: installing this package —
4
+ #
5
+ # dsh plugin --profile <name> add @dsh-ft/dsh-fft-plot
6
+ #
7
+ # — appends this single `insert` to the bundle stack.
8
+ #
9
+ # The row only needs the skill registry. The plotting scripts run on the DSH
10
+ # bundled Python (standard library only), so the row must not declare an
11
+ # FTShare settings service or any credentials handle.
12
+ - insert:
13
+ - id: dsh-fft-plot
14
+ name: '@dsh-ft/dsh-fft-plot'
package/locale/en.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "FT Plot",
4
+ "description": "Render FTShare query results as inline SVG charts."
5
+ }
6
+ }
package/locale/zh.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "FT 绘图",
4
+ "description": "把 FTShare 取数结果画成内联 SVG 图表。"
5
+ }
6
+ }
package/package.json CHANGED
@@ -1,6 +1,46 @@
1
1
  {
2
2
  "name": "@dsh-ft/dsh-fft-plot",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "FTShare data plotting for DeepSeek Harness: a bundled skill that renders query results into inline SVG charts with zero third-party dependencies.",
5
+ "license": "MIT",
6
+ "author": "Ben <ben@ft.tech>",
7
+ "homepage": "https://github.com/gigaflw/dsh-fft-base/tree/dev/packages/dsh-fft-plot#readme",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/gigaflw/dsh-fft-base.git",
11
+ "directory": "packages/dsh-fft-plot"
12
+ },
13
+ "bugs": {
14
+ "url": "https://github.com/gigaflw/dsh-fft-base/issues"
15
+ },
16
+ "type": "module",
17
+ "main": "src/index.js",
18
+ "exports": {
19
+ ".": "./src/index.js",
20
+ "./cordis.patch.yml": "./cordis.patch.yml",
21
+ "./package.json": "./package.json",
22
+ "./locale/*.json": "./locale/*.json"
23
+ },
24
+ "files": [
25
+ "src",
26
+ "skills",
27
+ "!skills/**/__pycache__",
28
+ "locale/*.json",
29
+ "cordis.patch.yml",
30
+ "README.md"
31
+ ],
32
+ "scripts": {
33
+ "test": "node --test tests/*.test.mjs"
34
+ },
35
+ "dsh": {
36
+ "bundle": {
37
+ "patch": "./cordis.patch.yml"
38
+ }
39
+ },
40
+ "peerDependencies": {
41
+ "@deepseek-ai/dsh-skill": ">=0.2.0-rc.2"
42
+ },
43
+ "engines": {
44
+ "node": ">=22.19.0"
45
+ }
46
+ }
@@ -0,0 +1,144 @@
1
+ ---
2
+ name: dsh-fft-plot
3
+ description: 把 FTShare 接口返回的数据渲染成图,图直接显示在聊天流里(内联 SVG,无需点开侧栏)。用于热榜、板块、资金流、估值、财报、宏观、指数等结果的趋势、排名、分布、对比。当用户说画图/出图/可视化/来张图,或在分析金融数据后需要更直观呈现时使用。
4
+ ---
5
+
6
+ # dsh-fft-plot:数据 → 内联图
7
+
8
+ ## 一句话流程
9
+
10
+ ```
11
+ 取到 rows(已经是扁平行数组)
12
+ → 写一个 spec.json(选图型 + 映射列名)
13
+ → plot.py --spec spec.json --out /绝对路径/chart.svg
14
+ → 在回复里写 ![说明](/绝对路径/chart.svg)
15
+ ```
16
+
17
+ 图会直接出现在聊天流中间。**不要**调用 `present`,也不要点开侧栏。
18
+
19
+ ## 必守的五条
20
+
21
+ 1. **产物路径必须是绝对路径**(`/` 开头)。Markdown 图片语法里的相对路径不会渲染。
22
+ 2. **图直接内联,不要 present**。产物写进 `![](/abs/path.svg)`,图会出现在回复中间;
23
+ 不要调用 `present` 让用户另外点开侧栏——那多一次点击,而这里要的就是一眼看到。
24
+ 3. **图前后要有文字**。图是论点的配图,不是答复本身——图前一句交代看什么,图后一句给结论。
25
+ 4. **不适用的情形不画**:数据为空、只有一条记录、纯名录字段、或用户只要一个数字。
26
+ 这时直接说结论,不要为了出图而出图。
27
+ 5. **不编造数字**。图上每个数字都必须来自 `rows`。
28
+
29
+ ## 三步
30
+
31
+ ### 1. 判断该不该画
32
+
33
+ | 该画 | 不该画 |
34
+ |---|---|
35
+ | 有时间趋势(净值、热度、估值序列、宏观) | 纯名录/字典(基金列表、成分股清单) |
36
+ | 有横截面排名(热榜、板块涨幅、龙虎榜) | 只有 1 条记录(1 根蜡烛没意义) |
37
+ | 有几项可比(分组收益、多期限收益率) | 字段含义不明(不知道单位是元还是万元) |
38
+ | 用户明确说画图 | 用户只要一个数字或一句话结论 |
39
+
40
+ ### 2. 选图型
41
+
42
+ | type | 用在哪 | 必填字段 |
43
+ |---|---|---|
44
+ | `line` | 时序趋势:热度衰减、净值曲线、估值分位、宏观指标 | `x`、`series` |
45
+ | `barh` | 横截面排名:热榜、板块涨幅、个股贡献 | `label`、`value` |
46
+ | `table` | 名录类数据,或作为图的补充 | `columns` |
47
+
48
+ ### 3. 写 spec 并渲染
49
+
50
+ ```bash
51
+ python3 <skill目录>/scripts/plot.py --spec /abs/spec.json --out /abs/chart.svg
52
+ ```
53
+
54
+ spec 是 **JSON**(不是 YAML)。数据少就内联 `rows`,多就写 `data` 指向 json 文件。
55
+
56
+ ## spec 结构
57
+
58
+ ```json
59
+ {
60
+ "theme": "paper",
61
+ "width": 1200,
62
+ "height": 560,
63
+ "data": "rows.json",
64
+ "chart": { "type": "barh", "...": "见下表" },
65
+ "legend": "条形长度=热度值;颜色=当日涨跌(红涨蓝跌)",
66
+ "notes": ["**主结论一行", "!强调色结论", "*小字口径说明"],
67
+ "sources": ["ft_v1_ths_hot_list"],
68
+ "sample": "样本:20260810 当日榜单前 10 条"
69
+ }
70
+ ```
71
+
72
+ **页头全部可选**(`chip` / `title` / `subtitle`)。图在聊天流中间时,前后已有文字说明,
73
+ **默认不写标题**,绘图区会占满。
74
+
75
+ `notes` 前缀:`**` 加粗主结论、`!` 红字强调、`*` 小字注释、无前缀为普通灰字。
76
+
77
+ ## 各图型字段
78
+
79
+ ### line
80
+
81
+ ```json
82
+ {"type":"line","x":"trade_date","x_kind":"category",
83
+ "series":[{"col":"hotValue","label":"热度","color":"down"}],
84
+ "area":true,
85
+ "marks":["20260810","20261110"],
86
+ "annotate":[{"x":"20261110","text":"名次 #3","dy":16}],
87
+ "refs":[{"y":50,"label":"五五开"}],
88
+ "band":{"lo":"p25","hi":"p75","label":"中间一半分布"},
89
+ "y_fmt":"num","y_dec":0}
90
+ ```
91
+
92
+ - `x_kind`:**日期列必须写 `"category"`**。日期若写成 `20260810` 这种可解析整数,
93
+ 按数值画会导致交易日间距忽宽忽窄(跨周末的间隔是 3 而不是 1)。
94
+ 纯数值轴(天数、比率)才用 `"auto"`。
95
+ - `series[].color`:主题键 `up`/`down`/`neutral`/`accent`/`band`,或 `#RRGGBB`。
96
+ - `band`:分布带,用于给出离散度而不是只有均值。
97
+ - `refs`:参考线(50%、0、基准值)。
98
+ - `marks`:要打点的 x 值,会标出数值。
99
+
100
+ ### barh
101
+
102
+ ```json
103
+ {"type":"barh","label":"name","value":"hotValue","sign":"riseAndFall",
104
+ "rank":"rank","top":10,"fmt":"compact","dec":1}
105
+ ```
106
+
107
+ - `sign`:决定颜色的列(正红负蓝的金融惯例)。不给则整组同色。
108
+ - `fmt`:`compact`(524.9万,**推荐**)、`num`(5,248,899)、`pct`(+4.2%)。
109
+ 用 `compact` 时把单位写进数值,就不必再单独加一行"单位是…"的说明。
110
+
111
+ ### table
112
+
113
+ ```json
114
+ {"type":"table","top":12,"font_size":13,"row_height":32,
115
+ "columns":[
116
+ {"col":"rank","label":"名次","weight":0.5,"align":"right"},
117
+ {"col":"name","label":"名称","weight":1.1},
118
+ {"col":"hotValue","label":"热度值","weight":1.0,"align":"right","dec":0}]}
119
+ ```
120
+
121
+ - `weight`:列宽比例;`align`:`left`/`right`;`dec`:小数位。
122
+
123
+ ## 数据形状的坑
124
+
125
+ 上游返回的字段与单位不统一,映射前先确认:
126
+
127
+ - **比率二义**:`turnover_rate=0.0123` 是小数,`riseAndFall=15.07` 是百分数。
128
+ 图上的 `y_fmt: "pct"` 只负责加 `%`,**不负责乘 100**——先看清原始量纲。
129
+ - **时间有五种写法**:毫秒时间戳、纳秒时间戳、`20260810`、`2026-08-10`、
130
+ `2026-09-30 00:00:00`。纳秒按毫秒解析会得到公元 5 万年。
131
+ - **列集可能随行变化**:`y_30y` 这类列只在部分行出现,按首行建列会静默丢数据。
132
+ - **分页**:很多接口默认只返回第一页。横截面分布用第一页画会系统性失真,
133
+ 要么按全量取,要么在图里写明样本范围。
134
+
135
+ ## 配色
136
+
137
+ `paper`(米白+朱红墨蓝,默认)、`poster`(纯白+亮橙)、`slate`(冷灰+青红)。
138
+ 所有主题都是浅色底:SVG 内联进聊天时读不到宿主的深色模式,浅色底保证永不错色。
139
+
140
+ ## 新增图型
141
+
142
+ `scripts/ftplot/charts.py` 里写一个函数加 `@chart('名字')` 即可,签名
143
+ `(c, rect, cfg, rows)`。然后在本文的图型表里补一行字段说明。
144
+ **不需要**改 `plot.py` 或任何布局代码。
@@ -0,0 +1,5 @@
1
+ """ft-plot 绘图内核:主题、SVG 画布、图型注册表、spec 解析。"""
2
+
3
+ from . import canvas, charts, spec, theme # noqa: F401
4
+
5
+ __all__ = ['canvas', 'charts', 'spec', 'theme']
@@ -0,0 +1,283 @@
1
+ """SVG 画布与坐标系。只用标准库,输出可被 `<img>` 直接加载的独立 SVG。
2
+
3
+ 设计要点:
4
+
5
+ - **坐标**:对外一律用像素(左上角原点,y 向下),内部换算成 SVG 属性。
6
+ - **尺寸**:由 spec 决定(默认 1200x700 横版),不是模块常量,所以同一套图元能出
7
+ 聊天内联横图、竖版长图或方图。
8
+ - **文本**:用真实 `<text>` 而非路径,文字可选中、可搜索,体积也只有路径的几分之一。
9
+ 中文字体由 `font-family` 回退链解析——SVG 在 `<img>` 里是独立文档,继承不到宿主字体。
10
+ - **不依赖任何第三方包**:没有 matplotlib、没有 numpy。
11
+ """
12
+ import math
13
+ import os
14
+
15
+ from .theme import FONT_STACK
16
+
17
+
18
+ # ---------------------------------------------------------------- 基础工具
19
+
20
+ def esc(s):
21
+ """转义 XML 文本内容。"""
22
+ return (str(s).replace('&', '&amp;').replace('<', '&lt;').replace('>', '&gt;'))
23
+
24
+
25
+ def nice_ticks(lo, hi, target=5):
26
+ """生成 1/2/2.5/5 x 10^n 步长的整齐刻度,落在 [lo, hi] 区间内。"""
27
+ if hi <= lo:
28
+ return [lo]
29
+ raw = (hi - lo) / max(target, 1)
30
+ mag = 10 ** math.floor(math.log10(raw))
31
+ step = mag
32
+ for mult in (1, 2, 2.5, 5, 10):
33
+ step = mult * mag
34
+ if step >= raw:
35
+ break
36
+ start = math.ceil(lo / step - 1e-9) * step
37
+ out, value = [], start
38
+ while value <= hi + step * 1e-9:
39
+ out.append(round(value, 10))
40
+ value += step
41
+ return out
42
+
43
+
44
+ def fmt_date_label(raw, compact=True):
45
+ """把返回里常见的日期写法收敛成短标签。
46
+
47
+ 上游日期有五种互不兼容形态(`20260810`、`2026-08-10`、`2026-09-30 00:00:00`、
48
+ 毫秒/纳秒时间戳、`2026年09月份`),8 位数字直接当轴标签既挤又难读。
49
+ `compact=True` 时同一年内只留「月-日」,跨年时保留年份。
50
+ """
51
+ text = str(raw).strip()
52
+ digits = ''.join(ch for ch in text if ch.isdigit())
53
+ if len(digits) == 8 and text[:4].isdigit():
54
+ year, month, day = digits[:4], digits[4:6], digits[6:8]
55
+ return f'{month}-{day}' if compact else f'{year}-{month}-{day}'
56
+ if len(digits) == 6 and len(text) <= 7: # 202609 -> 年月
57
+ return f'{digits[:4]}-{digits[4:6]}'
58
+ # `2026-09-30 00:00:00` 之类:去掉时间部分
59
+ if ' ' in text and len(text.split(' ')[0]) == 10:
60
+ return text.split(' ')[0] if not compact else text[5:10]
61
+ return text
62
+
63
+
64
+ def has_multiple_years(values):
65
+ """判断一组日期标签是否跨年——跨年就不能只写月-日。"""
66
+ years = set()
67
+ for raw in values:
68
+ digits = ''.join(ch for ch in str(raw) if ch.isdigit())
69
+ if len(digits) >= 6 and str(raw).strip()[:4].isdigit():
70
+ years.add(digits[:4])
71
+ return len(years) > 1
72
+
73
+
74
+ def fmt_num(value, dec=0):
75
+ """千分位数字;-0 归一成 0。"""
76
+ if abs(value) < 10 ** (-(dec + 6)):
77
+ value = 0.0
78
+ return f'{value:,.{dec}f}'
79
+
80
+
81
+ def fmt_pct(value, dec=1, signed=False):
82
+ """百分比;默认不补尾零,`signed=True` 时正数带 `+`。"""
83
+ text = f'{value:.{dec}f}'
84
+ if '.' in text:
85
+ text = text.rstrip('0').rstrip('.')
86
+ if signed and value > 0:
87
+ text = '+' + text
88
+ return f'{text}%'
89
+
90
+
91
+ def fmt_compact(value, dec=1):
92
+ """紧凑数值:把 5,248,899 写成 524.9万。
93
+
94
+ 单位直接进数值,图上就不必再写一行「单位是…」的说明——那行说明正是最容易和
95
+ 结论行撞在一起的元素。热榜热度、成交额、市值这类量级都适用。
96
+ """
97
+ magnitude = abs(value)
98
+ if magnitude >= 1e8:
99
+ return f'{value / 1e8:,.{dec}f}亿'
100
+ if magnitude >= 1e4:
101
+ return f'{value / 1e4:,.{dec}f}万'
102
+ if dec == 0:
103
+ return fmt_num(value, 0)
104
+ return f'{value:,.{dec}f}'.rstrip('0').rstrip('.')
105
+
106
+
107
+ def text_width(text, size):
108
+ """估算文本像素宽度:全角按 1.0em,半角按 0.55em。
109
+
110
+ 仅用于溢出检查与换行决策;实际对齐交给 SVG 的 `text-anchor`,
111
+ 所以估算偏一点不会让文字错位。
112
+ """
113
+ width = 0.0
114
+ for ch in str(text):
115
+ width += size * (1.0 if _is_wide(ch) else 0.55)
116
+ return width
117
+
118
+
119
+ def _is_wide(ch):
120
+ """是否全角/宽字符。"""
121
+ code = ord(ch)
122
+ return (
123
+ 0x1100 <= code <= 0x115F
124
+ or 0x2E80 <= code <= 0xA4CF
125
+ or 0xAC00 <= code <= 0xD7A3
126
+ or 0xF900 <= code <= 0xFAFF
127
+ or 0xFE30 <= code <= 0xFE6F
128
+ or 0xFF00 <= code <= 0xFF60
129
+ or 0xFFE0 <= code <= 0xFFE6
130
+ or 0x20000 <= code <= 0x3FFFD
131
+ )
132
+
133
+
134
+ def wrap(text, size, max_width):
135
+ """按估算宽度折行,优先在空格处断,其次逐字断。返回行列表。"""
136
+ if text_width(text, size) <= max_width:
137
+ return [text]
138
+ lines, current = [], ''
139
+ for ch in str(text):
140
+ candidate = current + ch
141
+ if text_width(candidate, size) > max_width and current:
142
+ lines.append(current)
143
+ current = ch
144
+ else:
145
+ current = candidate
146
+ if current:
147
+ lines.append(current)
148
+ return lines
149
+
150
+
151
+ # ---------------------------------------------------------------- 画布
152
+
153
+ class Svg:
154
+ """一个 SVG 文档。所有方法只追加元素,最后由 `save()` 落盘。"""
155
+
156
+ def __init__(self, width, height, theme):
157
+ self.w = width
158
+ self.h = height
159
+ self.t = theme
160
+ self.ops = []
161
+
162
+ # ---- 图元 ----
163
+
164
+ def rect(self, x, y, w, h, fill, rx=0, opacity=None):
165
+ attrs = f'x="{x:.2f}" y="{y:.2f}" width="{max(w, 0):.2f}" height="{max(h, 0):.2f}"'
166
+ if rx:
167
+ attrs += f' rx="{rx}"'
168
+ if opacity is not None:
169
+ attrs += f' opacity="{opacity}"'
170
+ self.ops.append(f'<rect {attrs} fill="{fill}"/>')
171
+
172
+ def line(self, x1, y1, x2, y2, stroke, width=1, dash=None, opacity=None):
173
+ attrs = f'x1="{x1:.2f}" y1="{y1:.2f}" x2="{x2:.2f}" y2="{y2:.2f}"'
174
+ if dash:
175
+ attrs += f' stroke-dasharray="{dash}"'
176
+ if opacity is not None:
177
+ attrs += f' opacity="{opacity}"'
178
+ self.ops.append(f'<line {attrs} stroke="{stroke}" stroke-width="{width}"/>')
179
+
180
+ def path(self, d, fill='none', stroke=None, width=2, opacity=None, dash=None):
181
+ attrs = f'd="{d}" fill="{fill}"'
182
+ if stroke:
183
+ attrs += (f' stroke="{stroke}" stroke-width="{width}"'
184
+ ' stroke-linejoin="round" stroke-linecap="round"')
185
+ if opacity is not None:
186
+ attrs += f' opacity="{opacity}"'
187
+ if dash:
188
+ attrs += f' stroke-dasharray="{dash}"'
189
+ self.ops.append(f'<path {attrs}/>')
190
+
191
+ def polyline(self, points, stroke, width=2.5, opacity=None, dash=None):
192
+ """points: [(x, y), ...] 像素坐标。"""
193
+ if len(points) < 2:
194
+ return
195
+ d = ' '.join(f'{x:.2f},{y:.2f}' for x, y in points).replace(' ', ' L ')
196
+ self.path(f'M {d}', stroke=stroke, width=width, opacity=opacity, dash=dash)
197
+
198
+ def polygon(self, points, fill, opacity=None):
199
+ """闭合多边形(面积带/面积图)。"""
200
+ if len(points) < 3:
201
+ return
202
+ coords = ' '.join(f'{x:.2f},{y:.2f}' for x, y in points).replace(' ', ' L ')
203
+ self.path(f'M {coords} Z', fill=fill, opacity=opacity)
204
+
205
+ def circle(self, cx, cy, r, fill, stroke=None, stroke_width=2):
206
+ attrs = f'cx="{cx:.2f}" cy="{cy:.2f}" r="{r}"'
207
+ if stroke:
208
+ attrs += f' stroke="{stroke}" stroke-width="{stroke_width}"'
209
+ self.ops.append(f'<circle {attrs} fill="{fill}"/>')
210
+
211
+ def text(self, x, y, s, size=14, fill=None, weight='normal', anchor='start',
212
+ baseline='auto', opacity=None):
213
+ """一段文本。`anchor`: start/middle/end;`baseline`: auto/middle/hanging。"""
214
+ attrs = (f'x="{x:.2f}" y="{y:.2f}" font-family="{FONT_STACK}" font-size="{size}"'
215
+ f' text-anchor="{anchor}" dominant-baseline="{baseline}"')
216
+ if weight != 'normal':
217
+ attrs += f' font-weight="{weight}"'
218
+ if opacity is not None:
219
+ attrs += f' opacity="{opacity}"'
220
+ self.ops.append(f'<text {attrs} fill="{fill or self.t["ink"]}">{esc(s)}</text>')
221
+
222
+ def text_block(self, x, y, lines, size=15, fill=None, weight='normal', anchor='start',
223
+ line_height=None):
224
+ """多行文本,返回下一行 y。"""
225
+ step = line_height or round(size * 1.55)
226
+ for i, line in enumerate(lines):
227
+ self.text(x, y + i * step, line, size=size, fill=fill, weight=weight, anchor=anchor)
228
+ return y + len(lines) * step
229
+
230
+ def save(self, path):
231
+ """写出 SVG,返回字节数。目录不存在则创建。"""
232
+ head = (f'<svg xmlns="http://www.w3.org/2000/svg" width="{self.w}" height="{self.h}"'
233
+ f' viewBox="0 0 {self.w} {self.h}" role="img">')
234
+ background = (f'<rect x="0" y="0" width="{self.w}" height="{self.h}"'
235
+ f' fill="{self.t["bg"]}"/>')
236
+ doc = '\n'.join([head, background, *self.ops, '</svg>', ''])
237
+ parent = os.path.dirname(os.path.abspath(path))
238
+ os.makedirs(parent, exist_ok=True)
239
+ with open(path, 'w', encoding='utf-8') as handle:
240
+ handle.write(doc)
241
+ return len(doc.encode('utf-8'))
242
+
243
+
244
+ # ---------------------------------------------------------------- 坐标系
245
+
246
+ class Axes:
247
+ """像素矩形内的数据坐标系。x 向右、y 向上(数据语义),对外换算成像素。"""
248
+
249
+ def __init__(self, svg, rect, x_domain, y_domain):
250
+ self.s = svg
251
+ self.x, self.y, self.w, self.h = rect
252
+ self.x0, self.x1 = x_domain
253
+ self.y0, self.y1 = y_domain
254
+
255
+ def px(self, value):
256
+ span = self.x1 - self.x0
257
+ return self.x + (0.0 if span == 0 else (value - self.x0) / span * self.w)
258
+
259
+ def py(self, value):
260
+ span = self.y1 - self.y0
261
+ return self.y + self.h - (0.0 if span == 0 else (value - self.y0) / span * self.h)
262
+
263
+ def points(self, xs, ys):
264
+ return [(self.px(x), self.py(y)) for x, y in zip(xs, ys)]
265
+
266
+ def grid_y(self, ticks, labels, color, label_size=13, dim=False):
267
+ """横向网格线 + 左侧刻度标签。"""
268
+ for tick, label in zip(ticks, labels):
269
+ y = self.py(tick)
270
+ if not dim or tick != 0:
271
+ self.s.line(self.x, y, self.x + self.w, y, color, 1)
272
+ self.s.text(self.x - 10, y, label, size=label_size, fill=self.s.t['mute'],
273
+ anchor='end', baseline='middle')
274
+
275
+ def baseline_y(self, value, color, width=1.5):
276
+ """零轴等强调线。"""
277
+ y = self.py(value)
278
+ self.s.line(self.x, y, self.x + self.w, y, color, width)
279
+
280
+ def labels_x(self, ticks, labels, color, size=13, offset=22):
281
+ for tick, label in zip(ticks, labels):
282
+ self.s.text(self.px(tick), self.y + self.h + offset, label, size=size,
283
+ fill=color, anchor='middle')