From d8702739758e3909c15c79080a23fcdf369bef9e Mon Sep 17 00:00:00 2001 From: mioupa <79833278+mioupa@users.noreply.github.com> Date: Tue, 10 Nov 2026 16:58:25 +0900 Subject: [PATCH 1/6] Record the 5b design and decisions (series style, annotations, fits) Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 1 + docs/PHASE5_DESIGN.md | 152 ++++++++++++++++++++++++++++++++++++++++++ docs/REQUIREMENTS.md | 5 ++ 3 files changed, 158 insertions(+) diff --git a/AGENTS.md b/AGENTS.md index 30dccf4..fce69e5 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -345,3 +345,4 @@ uv run pytest tests/e2e # E2E(Chromium とローカルの静的サー - X が日時の列のとき、X 軸の範囲を日時(`axes.x.dateMin` / `dateMax`)で指定できるようにした(§13.3 の「範囲の指定はできない」を改めた)。数値の範囲の欄は隠し、その値は使わない。対数軸との組み合わせはエラーのまま。 - U4: G7 → G8 の順(G7 の中は ステップ → 横棒 → 積み上げ棒 → ヒストグラム → 色分け散布図)。U5: G10 を使うときだけ scipy を読み込み、生成コードもそのときだけ scipy を使う(4.2 の例外。openpyxl と同じ扱い)。 - G6: 列は `[N]` か Excel の列記号(`A` = `[0]`)で参照する。式は許可した要素だけを自前で解釈し(`eval` を使わない)、生成コードは解釈した結果から決まった形で書く。 +- 5b(2026-11-10): 系列の複製は全設定を写し、色だけパレットの未使用の色にして直後に入れる(近似曲線は写さない)。近似曲線の式は「温度の近似: y = 1.234x + 5.678(R² = 0.9981)」(係数は有効数字4桁、R² は小数4桁で固定。「図の中」は左上に並べる)。文字列の X・棒グラフの X では、注釈の X は「何番目のカテゴリか(0 始まり)」。画面の「透明度」は「不透明度」(0〜1、alpha と同じ向き)と表示する。 diff --git a/docs/PHASE5_DESIGN.md b/docs/PHASE5_DESIGN.md index 02eb98f..2efadc1 100644 --- a/docs/PHASE5_DESIGN.md +++ b/docs/PHASE5_DESIGN.md @@ -285,3 +285,155 @@ ax.spines["top"].set_visible(False) # 上の枠線を消す 6. **U4**: グラフの種類は G7 → G8 の順でよいか。G7 の中は、ステップ → 横棒 → 積み上げ棒 → ヒストグラム → 色分け散布図の順を考えている。 7. **U5**: G10 は案 A(scipy を使うときだけ読み込み、生成コードもそのときだけ scipy を使う。4.2 の例外として記録)でよいか。 8. **G6 の列の書き方**: `[N]`(画面の列番号)と Excel の列記号(`B*1000`)の両方を使えるようにしてよいか。 + +--- + +## 5. 5b の詳細(G3 系列のスタイル、G4 注釈、G5 近似曲線、「注釈・解析」の区分) + +作成: 2026-11-10。オーナーが承認した(§5.9 の問いは、すべて提案どおりで決定)。 + +### 5.0 準備 + +- PR #5(5a)はまだ main にマージされていない。5b は `phase5a-axes` から `phase5b-annotations` を作り、その上に積む。5a がマージされたら main を取り込む。 +- スキーマは v4 のまま(§2.1)。新しい項目の既定値では、生成コードは Phase 4 と1文字も変わらない(`test_codegen_compat.py` で確かめる)。 + +### 5.1 追加する設定項目(v4 に足す) + +| キー | 既定値 | 受け付ける値・検証 | +|---|---|---| +| `series[].marker` | `"auto"` | `auto` / `none` / `o`(丸)/ `s`(四角)/ `^`(上三角)/ `v`(下三角)/ `D`(ひし形)/ `x` / `+` / `*`。棒グラフでは使わない | +| `series[].alpha` | 1 | 0〜1 の数(「系列Nの不透明度」)。1 のときは生成コードに何も書かない | +| `series[].fill` | `{lower: "", upper: "", alpha: 0.25}` | `lower` / `upper` は `""` か `__idx__N`。両方空なら帯なし、片方だけならエラー(「系列Nの塗りつぶし帯」)。`alpha` は 0〜1。棒グラフでは使わない | +| `annotations` | `[]` | 要素は下表。50 個まで | +| `fits` | `[]` | 要素は下表。20 本まで | + +注釈(`annotations[]`)の要素: + +| キー | 既定値 | 内容 | +|---|---|---| +| `id` | `a1`, `a2`, … | 削除しても再利用しない | +| `kind` | `"hline"` | `text`(文字)/ `hline`(水平線)/ `vline`(垂直線)/ `hspan`(横の帯: Y の範囲)/ `vspan`(縦の帯: X の範囲) | +| `text` | `""` | 文字(`text` だけ。200 文字まで。数式(mathtext)も使える) | +| `x` / `y` | `""` | 位置(`text` は x・y、`hline` は y、`vline` は x)。文字列で持つ(下記) | +| `start` / `end` | `""` | 帯の範囲(`hspan` は Y、`vspan` は X)。順不同 | +| `coords` | `"data"` | `data`(データの座標)/ `axes`(図の中の割合 0〜1)。`text` だけ | +| `axis` | `"y"` | `y` / `y2`。Y を使う種類で、第2Y軸を使うときだけ | +| `color` | `"#000000"` | 色 | +| `lineStyle` / `lineWidth` | `"dashed"` / 1 | 線(`hline` / `vline`)だけ | +| `alpha` | null | 0〜1。null は自動(帯 0.2、それ以外 1) | +| `fontSize` | null | 文字の大きさ(pt)。null は図のフォントサイズ | +| `label` | `""` | 凡例に出す名前(線と帯だけ)。空なら凡例に出さない | + +- 位置(`x` / `y` / `start` / `end`)は、入力欄の文字をそのまま持ち、dataprep が軸の種類で解釈する。数値の軸は数、日時の X は年が先頭の日付・日時(5a の日時の範囲と同じ解釈。`pd.Timestamp(...)` で書く)、文字列の X と棒グラフの X は「何番目のカテゴリか」(0 始まりの数。1.5 なら2つ目と3つ目の間)、図の中の割合は数。 +- 種類ごとに使わない項目は検証しない(§2.2)。 + +近似曲線(`fits[]`)の要素: + +| キー | 既定値 | 内容 | +|---|---|---| +| `id` | `f1`, `f2`, … | 削除しても再利用しない | +| `series` | 追加したときの系列1の id | 近似する系列の id。系列を削除したら、その系列の近似曲線も消す | +| `model` | `"linear"` | `linear`(1次式)/ `poly`(多項式) | +| `degree` | 2 | 2〜6 の整数。`poly` のときだけ | +| `show` | `"legend"` | 式と R² を `legend`(凡例)/ `text`(図の中)/ `none`(出さない。線だけ描く) | +| `color` | `""` | `""` は系列の色 | +| `lineStyle` | `"dashed"` | 線種。線幅は系列の線幅 | + +### 5.2 G3 系列のスタイル + +- **マーカー形状**: line の「自動」は今の動き(点サイズ > 0 なら丸)。形を選んで点サイズが自動のときは、散布図の自動と同じ面積 24 で描く(選んだのに見えない、を防ぐ)。「なし」は点サイズにかかわらず点を描かない(点サイズの欄を無効にする)。scatter の「自動」は今の丸。scatter の「なし」は点が見えなくなるので、日本語のエラーにする。 +- **不透明度**: `ax.plot` / `ax.scatter` / `ax.bar` に `alpha=0.5` を足す。エラーバーと塗りつぶし帯には効かない(帯は自分の不透明度を持つ)。欄の名前は「不透明度」(0〜1。1 は透けない)にする(下記の確認事項 4)。 +- **塗りつぶし帯**: line / scatter。下端・上端の列は系列のデータ元から選ぶ(§2.2)。値は下端・上端そのもの(誤差の大きさではない)。 + - `ax.fill_between(x[ok], lower[ok], upper[ok], color=系列の色, alpha=0.25, linewidth=0, label="_fill")`。凡例には出さない。 + - 下端・上端が欠けた行では帯が途切れる。数値にできない値は、エラーバーと同じく系列ごとに件数と例を警告する。 + - X が日時・文字列の列でも描ける(CPython で確認した)。第2Y軸の系列は `ax2` に描く。 + - 描く順は「塗りつぶし帯 → エラーバー → 系列本体 → 近似曲線」(§2.3)。 + - データ元を替えたら、下端・上端の列を空に戻し(帯は消える)、そのことをステータスの警告で知らせる。 +- **並べ替え・複製**: 系列カードの見出しに「↑」「↓」「複製」を足す(「削除」の左)。JS だけの操作(`state.js` の `moveSeries(id, delta)` / `duplicateSeries(id)`)。 + - 系列の順は、描く順・凡例の順・「系列N」の番号・複数系列の棒の並びに効く。Y が自動の系列は順に未使用の列が割り当たるので、並べ替えると変わることがある(今の規則のまま)。 + - 複製: すべての設定(エラーバー・塗りつぶし帯・マーカーを含む)を写し、id は新しく、色は今のパレットの未使用の色にして、元の系列の直後に入れる。近似曲線は写さない(確認事項 1)。 + +生成コードの例(line、マーカー・不透明度・塗りつぶし帯): + +```python +# 系列1: X = 時間 [0]、Y = 平均 [1] +x = pd.to_numeric(df.iloc[:, 0], errors="coerce") # 数値にできない値は NaN にする +y = pd.to_numeric(df.iloc[:, 1], errors="coerce") # 数値にできない値は NaN にする +ok = x.notna() & y.notna() # X か Y が欠けている行は描かない +fill_lower = pd.to_numeric(df.iloc[:, 2], errors="coerce") # 塗りつぶし帯の下端: 最小 [2] +fill_upper = pd.to_numeric(df.iloc[:, 3], errors="coerce") # 塗りつぶし帯の上端: 最大 [3] +ax.fill_between(x[ok], fill_lower[ok], fill_upper[ok], color="#FF4B00", alpha=0.25, linewidth=0, label="_fill") # 塗りつぶし帯(凡例には出さない) +ax.plot(x[ok], y[ok], color="#FF4B00", linewidth=2.0, linestyle="solid", marker="s", markersize=24 ** 0.5, alpha=0.8, label="平均") +``` + +### 5.3 G4 注釈 + +- 節「注釈」を、注釈があるときだけ「系列」と「軸」の間に入れる。以降の節の番号は1つずれる(注釈がなければ今と同じ番号)。このため `_Builder.section()` が番号を振るように変える(§2.3)。 +- 書き方: 文字は `ax.text(x, y, 文字, …)`(図の中の割合なら `transform=ax.transAxes`)、水平線・垂直線は `ax.axhline` / `ax.axvline`、帯は `ax.axhspan` / `ax.axvspan`(`linewidth=0`)。第2Y軸を選んだ水平線・横の帯・文字(データの座標)は `ax2` に描く。 +- 凡例: 名前を入れた線・帯を凡例に入れる(第2Y軸の分も、今の「まとめて凡例にする」書き方でまとまる)。凡例を出すかどうかの判定にも含める。 +- 検査(dataprep。日本語のエラー、`field` は「注釈Nの X」など): 未入力、数として読めない、日時として読めない(日時の X)、対数軸で 0 以下、日時の X なのに数を入れた(その逆も)。 +- 文字の数式の誤りは、今の数式のエラー(`field` は「数式」)になる。 +- 手順(`b.step`)に「注釈N」を足す。 + +```python +# ==== 5. 注釈 ==== +ax.axhline(100.0, color="#000000", linewidth=1.0, linestyle="dashed", label="基準値") # 注釈1: 水平線 +ax.axvspan(pd.Timestamp("2026-01-10 00:00:00"), pd.Timestamp("2026-01-12 00:00:00"), color="#000000", alpha=0.2, linewidth=0) # 注釈2: 縦の帯 +ax.text(0.05, 0.95, "ピーク", transform=ax.transAxes, color="#000000", fontsize=FONT_SIZE) # 注釈3: 文字(図の中の割合) +``` + +### 5.4 G5 近似曲線 + +- 計算は numpy の `np.polynomial.Polynomial.fit(x, y, 次数).convert()`(最小二乗。`np.polyfit` より、X の値が大きいときの桁落ちに強い。係数は低い次数から `fit.coef`)。R² は `1 - 残差平方和 / 全平方和`。 +- 描く範囲は、近似に使った点の X の最小〜最大を 200 点。系列と同じ Axes(第2Y軸なら `ax2`)に、系列の直後に描く(系列と同じ `x` / `y` / `ok` を使う)。 +- 式の文字は、生成コードの実行時に係数から作る。式を作る関数 `poly_text(coef)` を、式を表示するときだけスクリプトの冒頭に定義する(エラーバーの関数と同じ扱い)。係数は有効数字4桁(`.4g`)、R² は小数4桁。2次以上は `x$^{2}$` のように数式で上付きにする。利用者の文字列は、系列の名前(`literal()` を通す)だけ。 + - 凡例(`legend`): 線の名前を「温度の近似: y = 1.234x + 5.678($R^2$ = 0.9981)」にする。 + - 図の中(`text`): 左上に、近似曲線の順に並べて書く(位置は固定。`ax.text(0.03, 0.97 - 0.07 * 番号, …, transform=ax.transAxes, va="top")`、色は線と同じ)。線は凡例に出さない。 + - 出さない(`none`): 線だけ描き、凡例にも出さない。 +- 使えない場合(日本語のエラー): X が日時・文字列の系列、X の異なる値が「次数 + 1」個より少ない、Y がすべて同じ値(R² を計算できない)、系列が見つからない。棒グラフでは近似曲線を使わない(欄を隠す)。 +- 対数軸でも、近似は線形の値で行う(対数軸の上では曲がって見える)。そのことを欄の補足に書く。 +- 手順(`b.step`)に「近似曲線N」を足す。 + +```python +# 近似曲線1: 系列1(温度)の 1 次式(最小二乗。numpy) +fit = np.polynomial.Polynomial.fit(x[ok], y[ok], 1).convert() # 係数は低い次数から(fit.coef) +r2 = 1 - np.sum((y[ok] - fit(x[ok])) ** 2) / np.sum((y[ok] - y[ok].mean()) ** 2) # 決定係数 R² +x_fit = np.linspace(x[ok].min(), x[ok].max(), 200) # 近似曲線を描く X(データの範囲を 200 点) +ax.plot(x_fit, fit(x_fit), color="#FF4B00", linewidth=2.0, linestyle="dashed", label="温度の近似: " + poly_text(fit.coef) + f"($R^2$ = {r2:.4f})") +``` + +### 5.5 「注釈・解析」の区分と画面 + +- `#sectionAnalysis`(「体裁」と「保存」の間。既定で開く。折りたたみの状態は今の仕組みで残る)。 + - 注釈: 一覧 `#annotationList`、「+ 注釈を追加」`#addAnnotationBtn`。カード `annotation-` の入力欄は `-kind`、`-text`、`-coords`、`-x`、`-y`、`-start`、`-end`、`-axis`、`-color`、`-line-style`、`-line-width`、`-alpha`、`-font-size`、`-label`、`-remove`。種類で入力欄を出し分ける。X の欄の例は X の軸の種類で変える(数値「例 1.5」、日時「例 2026-01-31 12:00」、文字列「何番目か(0 始まり)」)。 + - 近似曲線: 一覧 `#fitList`、「+ 近似曲線を追加」`#addFitBtn`。カード `fit-` の入力欄は `-series`、`-model`、`-degree`、`-show`、`-color`(「系列の色」か、色を選ぶ)、`-line-style`、`-remove`。棒グラフでは一覧と追加ボタンを隠し、`#fitBarNote`(「棒グラフでは近似曲線は使えません」)を出す。 +- 系列カード: 「点の形」`series--marker`、「不透明度」`series--alpha`、折りたたみ「塗りつぶし帯」`
`(既定は閉じ、使っている系列は開いて作る)に `-fill-lower` / `-fill-upper` / `-fill-alpha`。見出しに `series--up` / `-down` / `-duplicate`。棒グラフでは点の形と塗りつぶし帯を隠す。 +- 色の入力は、系列と同じ色の選択(`colorPicker`)を使う。 +- 既存の E2E `test_panel_sections.py` の区分の一覧に「注釈・解析」を足す(§2.5 で決めた変更)。既存の要素の id は変えない。 + +### 5.6 設定を変えたときの追従 + +- 新しい項目は `load.*` でも `save.*` でもないので、今の振り分け(`bridge.js` の `routeChange`)で 250 ms 後の再描画になる。注釈・近似曲線の追加・削除(`annotation-list` / `fit-list` の通知)も同じ。コードタブ(GUI 同期・「最新でない」印・編集モード)の動きは 5a と同じ。 + +### 5.7 テスト + +- 単体: + - `test_settings.py`: 新しい既定値、検証と日本語エラー、隠れた項目を検証しないこと(種類ごとの注釈の項目、`linear` の次数、棒グラフの点の形・帯・近似曲線、第2Y軸を使わないときの `axis`)、上限(50 / 20)。`test_defaults_parity.py` に注釈・近似曲線の要素の既定値を足す。 + - 新しい `test_series_style.py`(点の形・不透明度・帯の生成コードを実行した artist、帯の欠損と警告、日時・文字列の X、第2Y軸)、`test_annotations.py`(種類ごとの artist と位置、日時の X、文字列の X の位置、図の中の割合、第2Y軸、凡例、対数軸の 0 以下、未入力・読めない値)、`test_fits.py`(係数と R² を numpy の直接計算と比べる、式の文字、表示先の3通り、点の不足・日時の X・一定の Y のエラー、第2Y軸)。 + - どれも「全体を実行した図」と「自動描画用の図」の要約が一致すること。コード注入(注釈の文字・名前、系列の名前、日時、列名のコメント)。既定の設定でコードの文面が Phase 4 と同じこと(`test_codegen_compat.py`)。 + - `runner.figure_summary` に、帯の数、各線の点の形、不透明度、注釈(文字・線・帯の数)、近似曲線の線と図の中の文字を足す。 + - `test_js_modules.py`: `moveSeries`、`duplicateSeries`(色・直後・近似曲線を写さない)、系列の削除で近似曲線も消えること、注釈・近似曲線の追加と既定値。 +- E2E: 新しい `test_series_style.py`(点の形・不透明度・帯・並べ替え・複製・棒グラフで隠れる・データ元の変更で帯の列が空になる)、`test_annotations.py`、`test_fits.py`。`test_panel_sections.py` を更新。 +- 生成コードの一致確認に、点の形・不透明度・帯(line)、帯と日時の X(scatter)、注釈(数値の X・日時の X・第2Y軸)、近似曲線(1次・凡例、多項式・図の中、第2Y軸)を足す。 + +### 5.8 計測(5b) + +- `tests/perf/bench.py` に `--only p5b` を足す: 10,000 行 × 5 系列で、全系列に塗りつぶし帯(列)と1次の近似曲線(凡例)を付け、注釈を3つ(水平線・縦の帯・文字)置いた状態で、タイトルを変えて再描画を測る(既存の「設定変更」と同じ方法)。 +- 見込み: CPython で、10,000 点の帯 5 本は約 +33 ms(帯なし 27 ms → 60 ms。凡例「best」の探索を含む)。ブラウザでは +100 ms 前後の見込みで、1 秒以内に収まる。近似の計算は数 ms。 + +### 5.9 確認したいこと + +1. **複製**: すべての設定を写し、色だけ今のパレットの未使用の色にして、元の系列の直後に入れる。近似曲線は写さない。これでよいか。 +2. **近似曲線の式の表示**: 「温度の近似: y = 1.234x + 5.678(R² = 0.9981)」の形(係数は有効数字4桁、R² は小数4桁で固定)。「図の中」は左上に並べる(位置は固定)。これでよいか。 +3. **文字列の X・棒グラフでの注釈の X の位置**は、「何番目のカテゴリか(0 始まり)」の数で指定する。これでよいか。 +4. **欄の名前**: 要件の「透明度」は、matplotlib の alpha(1 で透けない)に合わせて「不透明度」と表示する。これでよいか。 diff --git a/docs/REQUIREMENTS.md b/docs/REQUIREMENTS.md index f3d9556..61a5d4f 100644 --- a/docs/REQUIREMENTS.md +++ b/docs/REQUIREMENTS.md @@ -80,6 +80,11 @@ - U4: グラフの種類は G7 → G8 の順に足す。G7 の中は、ステップ → 横棒 → 積み上げ棒 → ヒストグラム → 色分け散布図の順。 - U5: G10(任意関数のフィッティング)を使うときだけ scipy を読み込む。生成コードも、そのときだけ scipy を使う(4.2 の「pandas・matplotlib・numpy だけ」の例外として、.xlsx の openpyxl と同じ扱いにする)。 - G6(式で新しい列): 列は `[N]`(画面の列番号)か Excel の列記号(`A` = `[0]`)で参照する。式は、許可した要素(数値、列、四則演算、べき乗、括弧、許可した関数)だけを自前で解釈し、`eval` などで実行しない。生成コードは、解釈した結果から決まった形で書く。 +- 5b(G3・G4・G5、2026-11-10): + - 系列の複製は、すべての設定を写し、色だけ今のパレットの未使用の色にして、元の系列の直後に入れる。近似曲線は写さない。 + - 近似曲線の式は「温度の近似: y = 1.234x + 5.678(R² = 0.9981)」の形で表示する(係数は有効数字4桁、R² は小数4桁で固定)。「図の中」に表示するときは左上に並べる(位置は固定)。計算は numpy の最小二乗(`np.polynomial.Polynomial.fit`)。 + - X が文字列の列と棒グラフの X では、注釈の X の位置を「何番目のカテゴリか(0 始まり)」の数で指定する。X が日時の列では日時で指定する。 + - G3 の「透明度」は、matplotlib の alpha(1 で透けない)に合わせて、画面では「不透明度」(0〜1)と表示する。 --- From 312137490f982643a02acedd9d69744ac5c82d54 Mon Sep 17 00:00:00 2001 From: mioupa <79833278+mioupa@users.noreply.github.com> Date: Tue, 10 Nov 2026 17:40:31 +0900 Subject: [PATCH 2/6] Add series markers, opacity, fill bands, annotations and fits to settings and generated code (Phase 5b) Co-Authored-By: Claude Opus 5.5 --- docs/PHASE5_DESIGN.md | 2 +- js/defaults.js | 27 +++ py/mplgui/codegen.py | 176 ++++++++++++++-- py/mplgui/dataprep.py | 288 +++++++++++++++++++++++++- py/mplgui/runner.py | 57 ++++++ py/mplgui/settings.py | 268 ++++++++++++++++++++++++- tests/unit/style_helpers.py | 82 ++++++++ tests/unit/test_annotations.py | 312 +++++++++++++++++++++++++++++ tests/unit/test_defaults_parity.py | 16 +- tests/unit/test_fits.py | 311 ++++++++++++++++++++++++++++ tests/unit/test_runner.py | 15 ++ tests/unit/test_series_style.py | 260 ++++++++++++++++++++++++ tests/unit/test_settings.py | 79 +++++++- 13 files changed, 1861 insertions(+), 32 deletions(-) create mode 100644 tests/unit/style_helpers.py create mode 100644 tests/unit/test_annotations.py create mode 100644 tests/unit/test_fits.py create mode 100644 tests/unit/test_series_style.py diff --git a/docs/PHASE5_DESIGN.md b/docs/PHASE5_DESIGN.md index 2efadc1..ea62062 100644 --- a/docs/PHASE5_DESIGN.md +++ b/docs/PHASE5_DESIGN.md @@ -371,7 +371,7 @@ ax.plot(x[ok], y[ok], color="#FF4B00", linewidth=2.0, linestyle="solid", marker= - 節「注釈」を、注釈があるときだけ「系列」と「軸」の間に入れる。以降の節の番号は1つずれる(注釈がなければ今と同じ番号)。このため `_Builder.section()` が番号を振るように変える(§2.3)。 - 書き方: 文字は `ax.text(x, y, 文字, …)`(図の中の割合なら `transform=ax.transAxes`)、水平線・垂直線は `ax.axhline` / `ax.axvline`、帯は `ax.axhspan` / `ax.axvspan`(`linewidth=0`)。第2Y軸を選んだ水平線・横の帯・文字(データの座標)は `ax2` に描く。 - 凡例: 名前を入れた線・帯を凡例に入れる(第2Y軸の分も、今の「まとめて凡例にする」書き方でまとまる)。凡例を出すかどうかの判定にも含める。 -- 検査(dataprep。日本語のエラー、`field` は「注釈Nの X」など): 未入力、数として読めない、日時として読めない(日時の X)、対数軸で 0 以下、日時の X なのに数を入れた(その逆も)。 +- 検査(dataprep。日本語のエラー、`field` は「注釈NのX」など): 未入力、数として読めない、日時として読めない(日時の X)、対数軸で 0 以下、日時の X なのに数を入れた(その逆も)。 - 文字の数式の誤りは、今の数式のエラー(`field` は「数式」)になる。 - 手順(`b.step`)に「注釈N」を足す。 diff --git a/js/defaults.js b/js/defaults.js index 8ba6706..e3ba3ad 100644 --- a/js/defaults.js +++ b/js/defaults.js @@ -36,8 +36,33 @@ export const DEFAULT_SERIES = { secondaryAxis: false, source: "", errorBars: { y: defaultErrorSpec(), x: defaultErrorSpec(), capSize: 3 }, + marker: "auto", + alpha: 1, + fill: { lower: "", upper: "", alpha: 0.25 }, }; +// 注釈(annotations[])1つの既定値。id は追加するときに a1, a2, ... を振る(削除しても再利用しない) +export const DEFAULT_ANNOTATION = { + id: "a1", + kind: "hline", + text: "", + x: "", + y: "", + start: "", + end: "", + coords: "data", + axis: "y", + color: "#000000", + lineStyle: "dashed", + lineWidth: 1, + alpha: null, + fontSize: null, + label: "", +}; + +// 近似曲線(fits[])1つの既定値。id は f1, f2, ...。series は追加するときに系列1の id にする +export const DEFAULT_FIT = { id: "f1", series: "s1", model: "linear", degree: 2, show: "legend", color: "", lineStyle: "dashed" }; + export const DEFAULT_SETTINGS = { version: SCHEMA_VERSION, load: { @@ -70,5 +95,7 @@ export const DEFAULT_SETTINGS = { y2: { label: "", scale: "linear", min: null, max: null, ...defaultTicks() }, }, series: [DEFAULT_SERIES], + annotations: [], + fits: [], save: { filename: "", format: "png", transparent: false, dpi: 300, svgText: "path" }, }; diff --git a/py/mplgui/codegen.py b/py/mplgui/codegen.py index a408777..caad467 100644 --- a/py/mplgui/codegen.py +++ b/py/mplgui/codegen.py @@ -13,7 +13,7 @@ from dataclasses import dataclass from typing import Callable -from .dataprep import AxisPlan, ErrorPlan, PlotPlan, SeriesPlan +from .dataprep import AnnotationPlan, AxisPlan, ErrorPlan, FitPlan, PlotPlan, SeriesPlan from .fonts import LATIN_FONTS, SANS_SERIF_PRIORITY from .formats import FORMATS, build_filename, savefig_kwargs, savefig_rc from .loader import DatetimeColumn, SourceInfo @@ -113,6 +113,7 @@ def __init__(self) -> None: self.steps: list[Step] = [] self.load_lines = (0, -1) self.output_lines = (0, -1) + self._section_count = 0 def add(self, *lines: str) -> None: self.lines.extend(lines) @@ -121,10 +122,11 @@ def blank(self) -> None: self.lines.append("") def section(self, title: str) -> int: - """区切りの見出しを書き、その行番号(1 始まり)を返す。""" + """区切りの見出し(番号は呼んだ順に自動で振る)を書き、その行番号(1 始まり)を返す。""" if self.lines: self.blank() - self.lines.append(f"# ==== {title} ====") + self._section_count += 1 + self.lines.append(f"# ==== {self._section_count}. {title} ====") return len(self.lines) def step(self, message: str, field: str | None = None): @@ -277,7 +279,7 @@ def _emit_read(b: _Builder, source: SourceInfo, data_file: str, df: str) -> None def _emit_load(b: _Builder, plan: PlotPlan, infos: list[SourceInfo]) -> None: - start = b.section("1. データの読み込み") + start = b.section("データの読み込み") if not plan.multi_source: _emit_read(b, infos[0], "DATA_FILE", "df") else: @@ -290,7 +292,7 @@ def _emit_load(b: _Builder, plan: PlotPlan, infos: list[SourceInfo]) -> None: def _emit_skip_rows(b: _Builder, plan: PlotPlan) -> None: - b.section("2. 描画に使う行") + b.section("描画に使う行") if plan.skip_rows > 0: for src in plan.sources: v = src.var @@ -300,7 +302,7 @@ def _emit_skip_rows(b: _Builder, plan: PlotPlan) -> None: def _emit_figure(b: _Builder, settings: Settings) -> None: - b.section("3. 図と軸") + b.section("図と軸") fig = settings.plot.figure w, h = literal(fig.width), literal(fig.height) if fig.unit == "in": @@ -363,6 +365,82 @@ def _style_args(s: SeriesSettings) -> str: return f"color={literal(s.color)}, linewidth={literal(s.line_width)}, linestyle={literal(s.line_style)}" +def _alpha_arg(p: SeriesPlan) -> str: + return f", alpha={literal(p.alpha)}" if p.alpha != 1.0 else "" + + +# ---- band (G3) ---- + + +def _emit_band(b: _Builder, s: SeriesSettings, p: SeriesPlan) -> None: + """塗りつぶし帯(fill_between)。エラーバーと系列本体より先に描く(系列本体が上に来る)。""" + fill = p.fill + if fill is None: + return + with b.step(f"系列{p.number}の塗りつぶし帯を描けませんでした。帯の下端・上端の列を確認してください。", f"系列{p.number}の塗りつぶし帯"): + b.add( + f'fill_lower = pd.to_numeric({p.data_var}.iloc[:, {fill.lower_index}], errors="coerce")' + f" # 塗りつぶし帯の下端: {comment_text(fill.lower_label)}", + f'fill_upper = pd.to_numeric({p.data_var}.iloc[:, {fill.upper_index}], errors="coerce")' + f" # 塗りつぶし帯の上端: {comment_text(fill.upper_label)}", + f"{_target(p)}.fill_between(x[ok], fill_lower[ok], fill_upper[ok], color={literal(s.color)}, alpha={literal(fill.alpha)}, " + 'linewidth=0, label="_fill") # 塗りつぶし帯(凡例には出さない)', + ) + + +# ---- fits (G5) ---- + +POLY_TEXT_FUNCTION = ( + "def poly_text(coef):", + ' """近似曲線の式の文字を作る(coef は低い次数から)。例: y = 1.234x$^{2}$ - 0.5x + 3.21(係数は有効数字4桁)"""', + ' text = "y = "', + " for power in range(len(coef) - 1, -1, -1):", + " c = float(coef[power])", + ' body = f"{abs(c):.4g}"', + " if power == 1:", + ' body += "x"', + " elif power >= 2:", + ' body += f"x$^{{{power}}}$"', + " if power == len(coef) - 1:", + ' text += ("-" if c < 0 else "") + body', + " else:", + ' text += (" - " if c < 0 else " + ") + body', + " return text", +) + + +def _uses_poly_text(plan: PlotPlan) -> bool: + return plan.plot_type in {"line", "scatter"} and any(f.show in {"legend", "text"} for f in plan.fits) + + +def _fit_label_expr(fit: FitPlan) -> str: + return f'{literal(fit.label_prefix + ": ")} + poly_text(fit.coef) + f"($R^2$ = {{r2:.4f}})"' + + +def _emit_fits(b: _Builder, plan: PlotPlan, p: SeriesPlan) -> None: + """系列本体の直後に、その系列の近似曲線を描く(系列と同じ x / y / ok を使う)。""" + for fit in plan.fits: + if fit.series_number != p.number: + continue + with b.step(f"近似曲線{fit.number}を描けませんでした。近似曲線の設定とデータを確認してください。", f"近似曲線{fit.number}"): + kind = "1 次式" if fit.degree == 1 else f"{fit.degree} 次式" + b.add( + f"# 近似曲線{fit.number}: 系列{p.number}({comment_text(fit.series_label)})の {kind}(最小二乗。numpy)", + f"fit = np.polynomial.Polynomial.fit(x[ok], y[ok], {fit.degree}).convert() # 係数は低い次数から(fit.coef)", + "r2 = 1 - np.sum((y[ok] - fit(x[ok])) ** 2) / np.sum((y[ok] - y[ok].mean()) ** 2) # 決定係数 R²", + "x_fit = np.linspace(x[ok].min(), x[ok].max(), 200) # 近似曲線を描く X(データの範囲を 200 点)", + ) + style = f"color={literal(fit.color)}, linewidth={literal(fit.line_width)}, linestyle={literal(fit.line_style)}" + label = _fit_label_expr(fit) if fit.show == "legend" else '"_fit"' + b.add(f"{fit.target}.plot(x_fit, fit(x_fit), {style}, label={label})") + if fit.show == "text": + y_pos = literal(round(0.97 - 0.07 * fit.text_index, 2)) + b.add( + f"{fit.target}.text(0.03, {y_pos}, {_fit_label_expr(fit)}, transform={fit.target}.transAxes, va=\"top\", " + f"color={literal(fit.color)}, fontsize=FONT_SIZE) # 近似曲線の式を図の中(左上)に書く" + ) + + # ---- error bars (G1) ---- ERROR_BAR_FUNCTION = ( @@ -482,12 +560,14 @@ def _emit_line_series(b: _Builder, settings: Settings, plan: PlotPlan) -> None: _emit_x_data(b, p) _emit_y_data(b, p) _emit_ok_mask(b) + _emit_band(b, s, p) _emit_line_error_bars(b, s, p) marker = "" - if p.marker_size > 0: + if p.marker: b.add("# 点の大きさ: 面積(scatter の s と同じ単位)の平方根を markersize(直径)にする") - marker = f', marker="o", markersize={literal(p.marker_size)} ** 0.5' - b.add(f"{_target(p)}.plot(x[ok], y[ok], {_style_args(s)}{marker}, label={literal(p.legend_label)})") + marker = f", marker={literal(p.marker)}, markersize={literal(p.marker_size)} ** 0.5" + b.add(f"{_target(p)}.plot(x[ok], y[ok], {_style_args(s)}{marker}{_alpha_arg(p)}, label={literal(p.legend_label)})") + _emit_fits(b, plan, p) def _emit_scatter_series(b: _Builder, settings: Settings, plan: PlotPlan) -> None: @@ -504,11 +584,14 @@ def _emit_scatter_series(b: _Builder, settings: Settings, plan: PlotPlan) -> Non _emit_x_data(b, p) _emit_y_data(b, p) _emit_ok_mask(b) + _emit_band(b, s, p) _emit_line_error_bars(b, s, p, zorder=1) # 点を上に描くため、エラーバーは zorder=1 + marker = f", marker={literal(p.marker)}" if p.marker else "" b.add( - f"{_target(p)}.scatter(x[ok], y[ok], color={literal(s.color)}, s={literal(p.marker_size)}, " - f"label={literal(p.legend_label)})" + f"{_target(p)}.scatter(x[ok], y[ok], color={literal(s.color)}, s={literal(p.marker_size)}{marker}" + f"{_alpha_arg(p)}, label={literal(p.legend_label)})" ) + _emit_fits(b, plan, p) def _emit_bar_x(b: _Builder, plan: PlotPlan) -> None: @@ -537,7 +620,7 @@ def _emit_bar_series(b: _Builder, settings: Settings, plan: PlotPlan) -> None: if p.y_err is not None: with b.step(*_error_step(p, p.y_err)): _emit_error_columns(b, p, p.y_err) - b.add(f"{_target(p)}.bar(x[ok], y[ok], {_style_args(s)}, label={literal(p.legend_label)}{_bar_error_args(s, p)})") + b.add(f"{_target(p)}.bar(x[ok], y[ok], {_style_args(s)}{_alpha_arg(p)}, label={literal(p.legend_label)}{_bar_error_args(s, p)})") return n = len(plan.series) @@ -572,7 +655,7 @@ def _emit_bar_series(b: _Builder, settings: Settings, plan: PlotPlan) -> None: b.add(f"offset = -0.4 + (width / 2.0) + ({i} * width)") b.add( f'{_target(p)}.bar(positions + offset, bar_data["y{p.number}"].fillna(0.0), width=width, ' - f"{_style_args(s)}, label={literal(p.legend_label)}{_bar_error_args(s, p, f'y{p.number}')})" + f"{_style_args(s)}{_alpha_arg(p)}, label={literal(p.legend_label)}{_bar_error_args(s, p, f'y{p.number}')})" ) @@ -584,10 +667,57 @@ def _emit_bar_series(b: _Builder, settings: Settings, plan: PlotPlan) -> None: def _emit_series(b: _Builder, settings: Settings, plan: PlotPlan) -> None: - b.section("4. 系列") + b.section("系列") SERIES_EMITTERS[plan.plot_type](b, settings, plan) +# ---- annotations (G4) ---- + +_ANNOTATION_NOTES = {"text": "文字", "hline": "水平線", "vline": "垂直線", "hspan": "横の帯", "vspan": "縦の帯"} + + +def _ann_x(a: AnnotationPlan, value) -> str: + """X 軸の値。日時の X なら pd.Timestamp(...)。""" + return f"pd.Timestamp({literal(value)})" if a.date else literal(float(value)) + + +def _ann_line_args(a: AnnotationPlan) -> str: + alpha = f", alpha={literal(a.alpha)}" if a.alpha is not None else "" + label = f", label={literal(a.label)}" if a.label else "" + return f"color={literal(a.color)}, linewidth={literal(a.line_width)}, linestyle={literal(a.line_style)}{alpha}{label}" + + +def _ann_span_args(a: AnnotationPlan) -> str: + alpha = literal(a.alpha if a.alpha is not None else 0.2) + label = f", label={literal(a.label)}" if a.label else "" + return f"color={literal(a.color)}, alpha={alpha}, linewidth=0{label}" + + +def _emit_annotations(b: _Builder, plan: PlotPlan) -> None: + b.section("注釈") + for a in plan.annotations: + v = a.target + note = _ANNOTATION_NOTES[a.kind] + ("(図の中の割合)" if a.kind == "text" and a.coords == "axes" else "") + with b.step(f"注釈{a.number}を描けませんでした。注釈の設定を確認してください。", f"注釈{a.number}"): + if a.kind == "hline": + code = f"{v}.axhline({literal(float(a.y))}, {_ann_line_args(a)})" + elif a.kind == "vline": + code = f"{v}.axvline({_ann_x(a, a.x)}, {_ann_line_args(a)})" + elif a.kind == "hspan": + code = f"{v}.axhspan({literal(float(a.start))}, {literal(float(a.end))}, {_ann_span_args(a)})" + elif a.kind == "vspan": + code = f"{v}.axvspan({_ann_x(a, a.start)}, {_ann_x(a, a.end)}, {_ann_span_args(a)})" + else: + size = literal(a.font_size) if a.font_size is not None else "FONT_SIZE" + alpha = f", alpha={literal(a.alpha)}" if a.alpha is not None else "" + style = f"color={literal(a.color)}, fontsize={size}{alpha}" + if a.coords == "axes": + code = f"{v}.text({literal(float(a.x))}, {literal(float(a.y))}, {literal(a.text)}, transform={v}.transAxes, {style})" + else: + code = f"{v}.text({_ann_x(a, a.x)}, {literal(float(a.y))}, {literal(a.text)}, {style})" + b.add(f"{code} # 注釈{a.number}: {note}") + + def _axis_lines(var: str, which: str, scale: str, lo, hi) -> list[str]: lines = [] if scale == "log": @@ -744,7 +874,7 @@ def _emit_spines(b: _Builder, settings: Settings, plan: PlotPlan) -> None: def _emit_axes(b: _Builder, settings: Settings, plan: PlotPlan) -> None: - b.section("5. 軸(ラベル・スケール・範囲・目盛)") + b.section("軸(ラベル・スケール・範囲・目盛)") plot, axes = settings.plot, settings.axes if plot.title: b.add(f"ax.set_title({literal(plot.title)}, fontsize=FONT_SIZE + 2)") @@ -795,7 +925,7 @@ def _emit_axes(b: _Builder, settings: Settings, plan: PlotPlan) -> None: def _emit_grid_and_legend(b: _Builder, settings: Settings, plan: PlotPlan) -> None: - b.section("6. グリッドと凡例") + b.section("グリッドと凡例") plot = settings.plot if plot.grid_minor and not _per_axis_minor(plan): # 軸ごとの副目盛の指定があるときは、5. 軸で書いた(minorticks_on() は軸ごとの指定を上書きする) b.add("ax.minorticks_on()") @@ -815,7 +945,10 @@ def _emit_grid_and_legend(b: _Builder, settings: Settings, plan: PlotPlan) -> No if plot.legend_location == "none": b.add("# 凡例は表示しない") return - if not any(p.has_points and p.legend_label and not p.legend_label.startswith("_") for p in plan.series): + labelled = any(p.has_points and p.legend_label and not p.legend_label.startswith("_") for p in plan.series) + labelled = labelled or any(a.label and not a.label.startswith("_") for a in plan.annotations) + labelled = labelled or any(f.show == "legend" for f in plan.fits) + if not labelled: b.add("# 凡例に出せるラベルが無い(空、または _ で始まる)ため、凡例は表示しない") return size = _label_size_expr(plot.font_size) @@ -832,7 +965,7 @@ def _emit_grid_and_legend(b: _Builder, settings: Settings, plan: PlotPlan) -> No def _emit_margins(b: _Builder, settings: Settings) -> None: - b.section("7. 余白") + b.section("余白") provided = settings.plot.margins.provided() if len(provided) < 4: b.add("# 余白は自動で調整する") @@ -861,7 +994,7 @@ def _emit_margins(b: _Builder, settings: Settings) -> None: def _emit_output(b: _Builder, settings: Settings) -> None: - start = b.section("8. 保存と表示") + start = b.section("保存と表示") save = settings.save _, _, ext = FORMATS[save.format] filename = build_filename(save.filename, ext) @@ -893,10 +1026,15 @@ def generate_script(settings: Settings, source, plan: PlotPlan) -> GeneratedScri if _uses_error_function(plan): b.blank() b.add(*ERROR_BAR_FUNCTION) + if _uses_poly_text(plan): + b.blank() + b.add(*POLY_TEXT_FUNCTION) _emit_load(b, plan, infos) _emit_skip_rows(b, plan) _emit_figure(b, settings) _emit_series(b, settings, plan) + if plan.annotations: + _emit_annotations(b, plan) _emit_axes(b, settings, plan) _emit_grid_and_legend(b, settings, plan) _emit_margins(b, settings) diff --git a/py/mplgui/dataprep.py b/py/mplgui/dataprep.py index 7994190..82e3dfe 100644 --- a/py/mplgui/dataprep.py +++ b/py/mplgui/dataprep.py @@ -16,6 +16,7 @@ from .loader import is_blank_cell as _is_blank_cell from .loader import looks_numeric as _looks_numeric from .settings import AxisSettings, ErrorSpec, Settings, check_axis_range, validate_date_range +from .settings import _DATE_EXAMPLE, _date_range_value, _to_float MAX_EXAMPLES = 3 NO_DRAWABLE_DATA = "描画可能なデータがありません。" @@ -156,6 +157,54 @@ class ErrorPlan: label_minus: str = "" +@dataclass(frozen=True) +class FillPlan: + """塗りつぶし帯(fill_between)。列は系列のデータ元の列番号(値は下端・上端そのもの)。""" + + lower_index: int + upper_index: int + lower_label: str # コメント用の列の表示(「名前 [番号]」) + upper_label: str + alpha: float + + +@dataclass(frozen=True) +class AnnotationPlan: + """解釈済みの注釈。位置は、軸の種類で解釈した値(数値は float、日時の X は正規化した日付の文字列)。""" + + number: int # 1 始まり + kind: str # text / hline / vline / hspan / vspan + text: str = "" + x: float | str | None = None # text(データ座標・図の中の割合)と vline の X + y: float | None = None # text と hline の Y + start: float | str | None = None # hspan は Y、vspan は X の範囲 + end: float | str | None = None + date: bool = False # X 軸の値(x / vspan の start・end)が日時(pd.Timestamp で書く) + coords: str = "data" # text だけ + target: str = "ax" # ax / ax2 + color: str = "#000000" + line_style: str = "dashed" + line_width: float = 1.0 + alpha: float | None = None # None = 自動(帯 0.2、それ以外 1) + font_size: float | None = None # None = FONT_SIZE + label: str = "" + + +@dataclass(frozen=True) +class FitPlan: + number: int # 1 始まり + series_number: int # 近似する系列の番号(1 始まり) + series_label: str # コメント・凡例名用の系列の名前 + degree: int # linear は 1 + show: str # legend / text / none + color: str # 実際に使う色("" だった場合は系列の色) + line_style: str + line_width: float + label_prefix: str # 凡例・図の中の文字の先頭(「温度の近似」) + text_index: int # show が text の近似曲線のうちの順番(0 始まり。それ以外は -1) + target: str # ax / ax2 + + @dataclass(frozen=True) class SeriesPlan: number: int # 1 始まり @@ -176,6 +225,9 @@ class SeriesPlan: y_err: ErrorPlan | None = None # Y 方向のエラーバー(指定が無ければ None) x_err: ErrorPlan | None = None # X 方向のエラーバー(line / scatter のみ) cap_size: float = 3.0 # エラーバーの端の線の長さ + marker: str = "" # line は描く点の形("" = 点なし)、scatter は "" = 既定の丸(引数を足さない) + alpha: float = 1.0 # 不透明度(1 のときはコードに書かない) + fill: FillPlan | None = None # 塗りつぶし帯(line / scatter のみ) @dataclass(frozen=True) @@ -236,6 +288,8 @@ class PlotPlan: sources: tuple[PlanSource, ...] = () # 描画に使うデータ元だけ(load.files の順) multi_source: bool = False # load.files が2つ以上(生成コードで DATA_FILE_N / dfN と書く) axes: AxesPlan = field(default_factory=AxesPlan) # 軸ごとの目盛の設定(効くものだけ) + annotations: tuple[AnnotationPlan, ...] = () + fits: tuple[FitPlan, ...] = () # 近似曲線(line / scatter のみ) @property def plotted(self) -> tuple[SeriesPlan, ...]: @@ -349,6 +403,222 @@ def _add_error_extent(ext: "_Extents", axis: str, base: pd.Series, plus, minus) ext.add_values(axis, base + plus) +# ---------------------------------------------------------------- series style (G3) + +DEFAULT_BAND_NOTE = "塗りつぶし帯" + + +def _marker_plan(series, plot_type: str) -> tuple[str, float]: + """点の形と点サイズ(面積)。line の「自動」は今までどおり(点サイズが 0 より大きいときだけ丸)。 + + 形を選んで点サイズが自動のときは、散布図と同じ面積 24 で描く。scatter の「自動」は引数を足さない。""" + shape = series.marker + if plot_type == "scatter": + return ("" if shape == "auto" else shape), series.effective_marker_size("scatter") + size = series.effective_marker_size("line") + if shape == "auto": + return ("o" if size > 0 else ""), size + if shape == "none": + return "", 0.0 + return shape, size if size > 0 else 24.0 + + +def _band_column(df: pd.DataFrame, requested: str, n: int) -> int: + field_name = f"系列{n}の塗りつぶし帯" + idx = parse_column_index(requested) + if idx is None: + raise UserError(f"系列{n}の塗りつぶし帯の列の指定が正しくありません。列を選び直してください。", field=field_name) + if idx >= len(df.columns): + raise UserError(_column_out_of_range(idx, len(df.columns)), field=field_name) + return idx + + +def _band_values(df: pd.DataFrame, idx: int, mask: pd.Series, n: int, what: str, load, warnings: list[dict]) -> pd.Series: + """帯の端の列を数値にする(数値にできない値は NaN。空欄も NaN で、警告しない)。警告の件数と例は、実際に描く行(mask)だけで数える。""" + raw = df.iloc[:, idx] + mask = mask.reindex(df.index, fill_value=False) + numeric, _, _ = coerce_numeric(raw) + _, count, examples = coerce_numeric(raw[mask]) + if count: + ex = ", ".join(f'"{e}"' for e in examples) + message = ( + f"系列{n}: 塗りつぶし帯({what})の列「{df.columns[idx]}」[{idx}] に数値にできない値が{count}件あったため、" + f"その点の帯は描きません(例: {ex})。{load_hint(examples, load)}" + ) + warnings.append({"series": n, "message": message}) + return numeric + + +def _plan_fill(df: pd.DataFrame, series, n: int, ok: pd.Series, y_axis: str, ext: "_Extents", load, warnings: list[dict]): + fill = series.fill + if not fill.enabled: + return None + lo_idx = _band_column(df, fill.lower, n) + hi_idx = _band_column(df, fill.upper, n) + lower = _band_values(df, lo_idx, ok, n, "下端", load, warnings) + upper = _band_values(df, hi_idx, ok, n, "上端", load, warnings) + both = lower.notna() & upper.notna() & ok.reindex(df.index, fill_value=False) + ext.add_values(y_axis, lower[both]) + ext.add_values(y_axis, upper[both]) + return FillPlan(lo_idx, hi_idx, _label_for(df, lo_idx)[1], _label_for(df, hi_idx)[1], fill.alpha) + + +# ---------------------------------------------------------------- fits (G5) + + +def _plan_fits(settings: Settings) -> list[tuple[int, object]]: + """(近似曲線の番号, FitSettings) を、系列の番号ごとに引けるように並べる。棒グラフでは使わない。""" + if settings.plot.type == "bar": + return [] + return list(enumerate(settings.fits, start=1)) + + +def _fit_error(n: int, message: str) -> UserError: + return UserError(f"近似曲線{n}: {message}", field=f"近似曲線{n}の系列") + + +def _check_fit_data(n: int, fit, p: "SeriesPlan", x: pd.Series, y: pd.Series) -> None: + """近似に使う点(x, y は描く行だけ)の検査。""" + if p.datetime_x: + raise _fit_error(n, "X が日時の列の系列は近似できません。") + if p.categorical_x: + raise _fit_error(n, "X が文字列の列の系列は近似できません。") + distinct = int(pd.Series(x).nunique()) + need = fit.degree + 1 + if distinct < need: + raise _fit_error(n, f"{fit.degree}次式で近似するには、X の異なる値が{need}個以上必要です(今は{distinct}個)。") + if int(pd.Series(y).nunique()) < 2: + raise _fit_error(n, "Y の値がすべて同じなので、近似できません(決定係数 R² を計算できません)。") + + +def _build_fit_plans(settings: Settings, plans: list["SeriesPlan"]) -> tuple[FitPlan, ...]: + ids = {s.id: i for i, s in enumerate(settings.series)} + out = [] + text_index = 0 + for n, fit in _plan_fits(settings): + i = ids[fit.series] + sp, ss = plans[i], settings.series[i] + if not sp.has_points: + raise _fit_error(n, "近似する系列に、描ける点がありません。") + base = sp.legend_label if not sp.legend_label.startswith("_") else f"系列{sp.number}" + out.append( + FitPlan( + number=n, + series_number=sp.number, + series_label=sp.legend_label, + degree=fit.degree, + show=fit.show, + color=fit.color or ss.color, + line_style=fit.line_style, + line_width=ss.line_width, + label_prefix=f"{base}の近似", + text_index=text_index if fit.show == "text" else -1, + target="ax2" if sp.secondary else "ax", + ) + ) + if fit.show == "text": + text_index += 1 + return tuple(out) + + +# ---------------------------------------------------------------- annotations (G4) + +_ANNOTATION_DATE_HELP = f"年が先頭の日付か日時で入力してください(例: {_DATE_EXAMPLE})" + + +def _annotation_value(text: str, n: int, what: str, *, kind: str, log: bool) -> float | str: + """注釈の位置の入力 → 値。kind は軸の種類(number / log / datetime / category)。datetime は正規化した日付の文字列、それ以外は float。""" + field_name = f"注釈{n}の{what}" # 「注釈1のX」「注釈1の開始」 + if not text.strip(): + raise UserError(f"{field_name}を入力してください。", field=field_name) + if kind == "datetime": + try: + return _date_range_value(text, "") + except UserError: + raise UserError( + f"{field_name}が正しくありません。X が日時の列なので、{_ANNOTATION_DATE_HELP}。", field=field_name + ) from None + value = _to_float(text) + if value is None: + if _looks_like_date(text): + raise UserError(f"{field_name}に日付は使えません。X が日時の列ではないので、数値で入力してください。", field=field_name) + hint = "(文字列の列では、何番目のカテゴリか(0 始まり)を数で指定します)" if kind == "category" else "" + raise UserError(f"{field_name}は数値で入力してください。{hint}", field=field_name) + if kind == "log" or log: + if value <= 0: + raise UserError(f"{field_name}は、対数軸では0より大きい値で入力してください。", field=field_name) + return value + + +def _looks_like_date(text: str) -> bool: + try: + _date_range_value(text, "") + except UserError: + return False + return True + + +def _plan_annotations(settings: Settings, x_kind: str, uses_secondary: bool, ext: "_Extents") -> tuple[AnnotationPlan, ...]: + out = [] + y_log = {"y": settings.axes.y.scale == "log", "y2": settings.axes.y2.scale == "log"} + for n, a in enumerate(settings.annotations, start=1): + use_y2 = a.axis == "y2" and uses_secondary + target = "ax2" if use_y2 else "ax" + y_axis = "y2" if use_y2 else "y" + common = dict( + number=n, kind=a.kind, target=target, color=a.color, alpha=a.alpha, label=a.label, line_style=a.line_style, + line_width=a.line_width, + ) + + def xval(text: str, what: str = "X") -> float | str: + return _annotation_value(text, n, what, kind=x_kind, log=False) + + def yval(text: str, what: str = "Y") -> float: + return _annotation_value(text, n, what, kind="log" if y_log[y_axis] else "number", log=False) # type: ignore[return-value] + + def add_x(*values) -> None: + if x_kind in {"number", "log"}: + nums = [float(v) for v in values] + ext.add("x", min(nums), max(nums)) + elif x_kind == "datetime": + secs = [_timestamp_seconds(v) for v in values] + ext.add("x", min(secs), max(secs)) + + def add_y(*values) -> None: + ext.add(y_axis, min(values), max(values)) + + if a.kind == "text": + if not a.text.strip(): + raise UserError(f"注釈{n}の文字を入力してください。", field=f"注釈{n}の文字") + if a.coords == "axes": + x = _annotation_value(a.x, n, "X", kind="number", log=False) + y = _annotation_value(a.y, n, "Y", kind="number", log=False) + out.append(AnnotationPlan(**common, text=a.text, x=x, y=y, coords="axes", font_size=a.font_size)) + else: + x = xval(a.x) + y = yval(a.y) + out.append( + AnnotationPlan(**common, text=a.text, x=x, y=y, coords="data", date=x_kind == "datetime", font_size=a.font_size) + ) + elif a.kind == "hline": + y = yval(a.y) + add_y(y) + out.append(AnnotationPlan(**common, y=y)) + elif a.kind == "vline": + x = xval(a.x) + add_x(x) + out.append(AnnotationPlan(**common, x=x, date=x_kind == "datetime")) + elif a.kind == "hspan": + lo, hi = yval(a.start, "開始"), yval(a.end, "終了") + add_y(lo, hi) + out.append(AnnotationPlan(**common, start=lo, end=hi)) + else: # vspan + lo, hi = xval(a.start, "開始"), xval(a.end, "終了") + add_x(lo, hi) + out.append(AnnotationPlan(**common, start=lo, end=hi, date=x_kind == "datetime")) + return tuple(out) + + NOT_LOADED_MESSAGE = "データ{n}({name})を読み込めていません。読込設定やファイルを確認してください。" BAR_SOURCE_MESSAGE = "棒グラフでは、すべての系列に同じデータ元を選んでください。" @@ -555,6 +825,8 @@ def _plan_xy(dfs: list[pd.DataFrame], settings: Settings, y_requests: list[str]) warnings: list[dict] = [] category_values: set = set() ext = _Extents() + fit_settings = _plan_fits(settings) + fits_of = {settings.series[i].id: [(k, f) for k, f in fit_settings if f.series == settings.series[i].id] for i in range(len(settings.series))} for n, (df, series, y_request) in enumerate(zip(dfs, settings.series, y_requests), start=1): x_index = resolve_column_index(df, series.x) if series.x else None x_label = str(df.columns[x_index]) if x_index is not None else "index" @@ -576,6 +848,7 @@ def _plan_xy(dfs: list[pd.DataFrame], settings: Settings, y_requests: list[str]) warnings.append(dropped_warning(n, f"系列{n}({y_name})", y_dropped, y_examples, settings.load)) has_points = bool((y_numeric.notna() & pd.notna(x_series)).any()) + marker, marker_size = _marker_plan(series, plot_type) plans.append( SeriesPlan( number=n, @@ -590,15 +863,20 @@ def _plan_xy(dfs: list[pd.DataFrame], settings: Settings, y_requests: list[str]) and not datetime_x and not convert_x and not pd.api.types.is_numeric_dtype(x_series.dtype), - marker_size=series.effective_marker_size(plot_type), + marker_size=marker_size, has_points=has_points, secondary=series.secondary_axis, datetime_x=datetime_x, + marker=marker, + alpha=series.alpha, ) ) if has_points: ok = y_numeric.notna() & pd.notna(x_series) y_axis = "y2" if series.secondary_axis else "y" + fill_plan = _plan_fill(df, series, n, ok, y_axis, ext, settings.load, warnings) + for k, fit in fits_of[series.id]: + _check_fit_data(k, fit, plans[-1], x_series[ok], y_numeric[ok]) ext.add_values(y_axis, y_numeric[ok]) if datetime_x: ext.add_values("x", _seconds(x_series[ok])) @@ -616,7 +894,7 @@ def _plan_xy(dfs: list[pd.DataFrame], settings: Settings, y_requests: list[str]) _add_error_extent(ext, y_axis, y_numeric[ok], _take(y_plus, ok), _take(y_minus, ok)) if x_err is not None: _add_error_extent(ext, "x", x_series[ok], _take(x_plus, ok), _take(x_minus, ok)) - plans[-1] = replace(plans[-1], y_err=y_err, x_err=x_err, cap_size=bars.cap_size) + plans[-1] = replace(plans[-1], y_err=y_err, x_err=x_err, cap_size=bars.cap_size, fill=fill_plan) if has_points and x_index is not None and plans[-1].categorical_x: shown = x_series[y_numeric.notna() & x_series.notna()] category_values.update(shown.tolist()) @@ -639,6 +917,7 @@ def _plan_xy(dfs: list[pd.DataFrame], settings: Settings, y_requests: list[str]) datetime_x=any(p.datetime_x and p.has_points for p in plans), thin_categorical_x=len(category_values) > MAX_CATEGORY_TICKS, axes_args=(x_kind, ext, len(category_values)), + fits=_build_fit_plans(settings, plans), ) @@ -696,6 +975,7 @@ def _plan_bar(df: pd.DataFrame, settings: Settings, y_requests: list[str]) -> Pl has_points=True, secondary=series.secondary_axis, datetime_x=datetime_x, + alpha=series.alpha, ) ) @@ -753,11 +1033,13 @@ def _finish( thin_categorical_x: bool = False, bar_date_format: str | None = None, axes_args: tuple[str, _Extents, int] | None = None, + fits: tuple[FitPlan, ...] = (), ) -> PlotPlan: primary = [p.data_label for p in plans if not p.secondary] secondary = [p.data_label for p in plans if p.secondary] uses_secondary = any(p.secondary and p.has_points for p in plans) x_kind, ext, categories = axes_args or ("number", _Extents(), 0) + annotations = _plan_annotations(settings, x_kind, uses_secondary, ext) # 範囲を ext に足すので、軸の計画より前 return PlotPlan( skip_rows=settings.plot.skip_rows, plot_type=settings.plot.type, @@ -773,4 +1055,6 @@ def _finish( thin_categorical_x=thin_categorical_x, bar_date_format=bar_date_format, axes=_plan_axes(settings, x_kind, uses_secondary, ext, categories), + annotations=annotations, + fits=fits, ) diff --git a/py/mplgui/runner.py b/py/mplgui/runner.py index 0e60add..e4db825 100644 --- a/py/mplgui/runner.py +++ b/py/mplgui/runner.py @@ -93,6 +93,62 @@ def _offset_text(axis) -> str: return str(get_offset()) if get_offset is not None else "" +_AUX_LINE_LABELS = {"_errorbar", "_fit"} + + +def _is_fit_label(label: str) -> bool: + return label == "_fit" or "$R^2$ = " in label + + +def _is_fit_text(text: str) -> bool: + return "y = " in text and "$R^2$ = " in text + + +def _transform_kind(artist, ax) -> tuple[bool, bool]: + """(X が データ座標か, Y が データ座標か)。axhline / axvline / axhspan / axvspan は片方だけデータ座標。""" + return tuple(bool(v) for v in artist.get_transform().contains_branch_seperately(ax.transData)) + + +def _series_lines(ax) -> list: + """系列の線(エラーバー・近似曲線・注釈の線を除く)。""" + return [ + ln for ln in ax.lines + if ln.get_label() not in _AUX_LINE_LABELS and not _is_fit_label(ln.get_label()) and _transform_kind(ln, ax) == (True, True) + ] + + +def _style_summary(ax) -> dict: + """点の形・不透明度・塗りつぶし帯・注釈・近似曲線の要約(既存のキーの値は変えない)。""" + lines = ax.lines + hlines = vlines = 0 + for ln in lines: + kind = _transform_kind(ln, ax) + hlines += kind == (False, True) + vlines += kind == (True, False) + hspans = vspans = 0 + for patch in ax.patches: + kind = _transform_kind(patch, ax) + hspans += kind == (False, True) + vspans += kind == (True, False) + fit_texts = sum(1 for t in ax.texts if _is_fit_text(t.get_text())) + series_lines = _series_lines(ax) + scatters = [c for c in ax.collections if type(c).__name__ == "PathCollection" and not c.get_label().startswith("_")] + return { + "bands": sum(1 for c in ax.collections if c.get_label() == "_fill"), + "markers": [str(ln.get_marker()) for ln in series_lines], + "alphas": [ln.get_alpha() for ln in series_lines] + [c.get_alpha() for c in scatters], + "annotations": { + "texts": len(ax.texts) - fit_texts, + "hlines": hlines, + "vlines": vlines, + "hspans": hspans, + "vspans": vspans, + }, + "fitlines": sum(1 for ln in lines if _is_fit_label(ln.get_label())), + "fittexts": fit_texts, + } + + def figure_summary(fig) -> list[dict]: """Figure の中身の要約(軸ごと)。JSON にできる値だけで、E2E と生成コードの一致確認に使う。""" out = [] @@ -126,6 +182,7 @@ def figure_summary(fig) -> list[dict]: "yoffset": _offset_text(ax.yaxis), "errorbars": sum(1 for line in ax.lines if line.get_label() == "_errorbar") + sum(1 for c in ax.containers if type(c).__name__ == "ErrorbarContainer"), + **_style_summary(ax), } ) return out diff --git a/py/mplgui/settings.py b/py/mplgui/settings.py index 5a8dc39..1e37686 100644 --- a/py/mplgui/settings.py +++ b/py/mplgui/settings.py @@ -57,6 +57,15 @@ ERROR_MODES = ("none", "fixed", "column") MAX_CAP_SIZE = 50 _COLUMN_RE = re.compile(r"__idx__[0-9]+") +MARKERS = ("auto", "none", "o", "s", "^", "v", "D", "x", "+", "*") +ANNOTATION_KINDS = ("text", "hline", "vline", "hspan", "vspan") +ANNOTATION_COORDS = ("data", "axes") +ANNOTATION_AXES = ("y", "y2") +FIT_MODELS = ("linear", "poly") +FIT_SHOWS = ("legend", "text", "none") +MAX_ANNOTATIONS = 50 +MAX_FITS = 20 +MAX_ANNOTATION_TEXT = 200 _DATE_INPUT_RE = re.compile(r"(\d{4})([-/])(\d{1,2})\2(\d{1,2})(?:[ T](\d{1,2}):(\d{2})(?::(\d{2}))?)?") DATE_RANGE_LABEL = "X軸の範囲(日時)" @@ -70,6 +79,26 @@ "inverted": False, } +_DEFAULT_FILL = {"lower": "", "upper": "", "alpha": 0.25} +_DEFAULT_ANNOTATION = { + "id": "a1", + "kind": "hline", + "text": "", + "x": "", + "y": "", + "start": "", + "end": "", + "coords": "data", + "axis": "y", + "color": "#000000", + "lineStyle": "dashed", + "lineWidth": 1, + "alpha": None, + "fontSize": None, + "label": "", +} +_DEFAULT_FIT = {"id": "f1", "series": "s1", "model": "linear", "degree": 2, "show": "legend", "color": "", "lineStyle": "dashed"} + _DEFAULT_SERIES = { "id": "s1", "x": "", @@ -82,9 +111,22 @@ "secondaryAxis": False, "source": "", "errorBars": {"y": copy.deepcopy(_DEFAULT_ERROR_SPEC), "x": copy.deepcopy(_DEFAULT_ERROR_SPEC), "capSize": 3}, + "marker": "auto", + "alpha": 1, + "fill": copy.deepcopy(_DEFAULT_FILL), } +def default_annotation() -> dict: + """注釈1つの既定値(js/defaults.js の DEFAULT_ANNOTATION と同一)。""" + return copy.deepcopy(_DEFAULT_ANNOTATION) + + +def default_fit() -> dict: + """近似曲線1つの既定値(js/defaults.js の DEFAULT_FIT と同一)。""" + return copy.deepcopy(_DEFAULT_FIT) + + def default_settings() -> dict: """既定の設定(JSON 互換の dict)。呼ぶたびに新しい dict を返す。""" return { @@ -122,6 +164,8 @@ def default_settings() -> dict: "y2": {"label": "", "scale": "linear", "min": None, "max": None, **copy.deepcopy(_DEFAULT_TICKS)}, }, "series": [copy.deepcopy(_DEFAULT_SERIES)], + "annotations": [], + "fits": [], "save": {"filename": "", "format": "png", "transparent": False, "dpi": DEFAULT_DPI, "svgText": "path"}, } @@ -236,6 +280,19 @@ class ErrorBarSettings: cap_size: float = 3.0 +@dataclass(frozen=True) +class FillSettings: + """塗りつぶし帯(fill_between)。lower / upper は "__idx__N"。両方空なら帯なし。""" + + lower: str = "" + upper: str = "" + alpha: float = 0.25 + + @property + def enabled(self) -> bool: + return bool(self.lower and self.upper) + + @dataclass(frozen=True) class SeriesSettings: id: str = "s1" @@ -249,6 +306,9 @@ class SeriesSettings: secondary_axis: bool = False source: str = "" # データ元のファイル id("" = load.files の先頭) error_bars: ErrorBarSettings = field(default_factory=ErrorBarSettings) + marker: str = "auto" # auto / none / o / s / ^ / v / D / x / + / *(棒グラフでは使わない) + alpha: float = 1.0 # 不透明度(1 = 透けない) + fill: FillSettings = field(default_factory=FillSettings) # 棒グラフでは使わない def effective_marker_size(self, plot_type: str) -> float: """自動(None)は line=0 / それ以外=24。scatter で 0 以下なら 24 に補正する。""" @@ -260,6 +320,38 @@ def effective_marker_size(self, plot_type: str) -> float: return float(size) +@dataclass(frozen=True) +class AnnotationSettings: + """注釈1つ。位置(x / y / start / end)は入力欄の文字のまま持つ(軸の種類で解釈するのは dataprep)。種類で使わない項目は既定値。""" + + id: str = "a1" + kind: str = "hline" # text / hline / vline / hspan / vspan + text: str = "" + x: str = "" + y: str = "" + start: str = "" + end: str = "" + coords: str = "data" # text だけ: data / axes + axis: str = "y" # y / y2(Y を使う種類で、第2Y軸を使うときだけ) + color: str = "#000000" + line_style: str = "dashed" + line_width: float = 1.0 + alpha: float | None = None # None = 自動(帯 0.2、それ以外 1) + font_size: float | None = None # None = 図のフォントサイズ + label: str = "" + + +@dataclass(frozen=True) +class FitSettings: + id: str = "f1" + series: str = "s1" # 系列の id + model: str = "linear" + degree: int = 1 # linear は 1、poly は 2〜6 + show: str = "legend" # legend / text / none + color: str = "" # "" = 系列の色 + line_style: str = "dashed" + + @dataclass(frozen=True) class SaveSettings: filename: str = "" @@ -277,6 +369,8 @@ class Settings: axes: AxesSettings = field(default_factory=AxesSettings) series: tuple[SeriesSettings, ...] = () save: SaveSettings = field(default_factory=SaveSettings) + annotations: tuple[AnnotationSettings, ...] = () + fits: tuple[FitSettings, ...] = () @property def uses_secondary_axis(self) -> bool: @@ -307,20 +401,22 @@ def _to_float(value: Any) -> float | None: def _number(value: Any, label: str, *, default: float | None = None, minimum: float | None = None, - exclusive_min: float | None = None, maximum: float | None = None, owner: str = "") -> float | None: + exclusive_min: float | None = None, maximum: float | None = None, owner: str = "", + field_name: str | None = None) -> float | None: """数値項目を検証する。空(None/空文字)は default を返す(None なら None)。""" name = f"{owner}「{label}」" + field_name = field_name or label if _is_blank(value): return default num = _to_float(value) if num is None: - raise UserError(f"{name}は数値で入力してください。", field=label) + raise UserError(f"{name}は数値で入力してください。", field=field_name) if exclusive_min is not None and num <= exclusive_min: - raise UserError(f"{name}は{_fmt(exclusive_min)}より大きい数値で入力してください。", field=label) + raise UserError(f"{name}は{_fmt(exclusive_min)}より大きい数値で入力してください。", field=field_name) if minimum is not None and num < minimum: - raise UserError(f"{name}は{_fmt(minimum)}以上の数値で入力してください。", field=label) + raise UserError(f"{name}は{_fmt(minimum)}以上の数値で入力してください。", field=field_name) if maximum is not None and num > maximum: - raise UserError(f"{name}は{_fmt(maximum)}以下の数値で入力してください。", field=label) + raise UserError(f"{name}は{_fmt(maximum)}以下の数値で入力してください。", field=field_name) return num @@ -353,9 +449,9 @@ def _boolean(value: Any, label: str, *, owner: str = "") -> bool: raise UserError(f"{owner}「{label}」の値が不正です。", field=label) -def _choice(value: Any, label: str, choices: tuple[str, ...], *, owner: str = "") -> str: +def _choice(value: Any, label: str, choices: tuple[str, ...], *, owner: str = "", field_name: str | None = None) -> str: if not isinstance(value, str) or value not in choices: - raise UserError(f"{owner}「{label}」の値が不正です。", field=label) + raise UserError(f"{owner}「{label}」の値が不正です。", field=field_name or label) return value @@ -641,6 +737,29 @@ def _parse_error_bars(raw: dict, plot_type: str, owner: str) -> ErrorBarSettings ) +def _parse_fill(raw: dict, owner: str) -> FillSettings: + field_name = f"{owner}塗りつぶし帯" + columns = [] + for key, what in (("lower", "下端"), ("upper", "上端")): + value = raw[key] + if value is None: + value = "" + if not isinstance(value, str): + raise UserError(f"{owner}「塗りつぶし帯の{what}」の指定が正しくありません。列を選び直してください。", field=field_name) + value = value.strip() + if value and not _COLUMN_RE.fullmatch(value): + raise UserError(f"{owner}「塗りつぶし帯の{what}」の指定が正しくありません。列を選び直してください。", field=field_name) + columns.append(value) + lower, upper = columns + if not lower and not upper: + return FillSettings() # 帯なし。不透明度は使わないので検証しない + if not lower or not upper: + missing = "下端" if not lower else "上端" + raise UserError(f"{owner}「塗りつぶし帯」は、下端と上端の両方の列を選んでください({missing}が未選択です)。", field=field_name) + alpha = _number(raw["alpha"], "塗りつぶし帯の不透明度", default=0.25, minimum=0, maximum=1, owner=owner, field_name=field_name) + return FillSettings(lower=lower, upper=upper, alpha=alpha) + + def _parse_series(raw_series: Any, plot_type: str = "line") -> tuple[SeriesSettings, ...]: if not isinstance(raw_series, list) or not raw_series: raise UserError("描画系列を1つ以上追加してください。", field="描画系列") @@ -659,6 +778,15 @@ def _parse_series(raw_series: Any, plot_type: str = "line") -> tuple[SeriesSetti raise UserError(f"{owner}「色」が不正です。", field="色") line_width = _number(s["lineWidth"], "線幅", default=2.0, exclusive_min=0, owner=owner) marker = _number(s["markerSize"], "点サイズ", default=None, minimum=0, owner=owner) + marker_shape = "auto" + fill = FillSettings() + if plot_type != "bar": # 棒グラフでは点の形と塗りつぶし帯を隠すので、検証せず使わない + marker_shape = _choice(s["marker"], "点の形", MARKERS, owner=owner, field_name=f"{owner}点の形") + if plot_type == "scatter" and marker_shape == "none": + raise UserError( + f"{owner}「点の形」を「なし」にすると、散布図の点が見えなくなります。点の形を選んでください。", field=f"{owner}点の形" + ) + fill = _parse_fill(s["fill"], owner) out.append( SeriesSettings( id=sid, @@ -672,6 +800,126 @@ def _parse_series(raw_series: Any, plot_type: str = "line") -> tuple[SeriesSetti secondary_axis=_boolean(s["secondaryAxis"], "第2軸を使用", owner=owner), source=_string(s["source"], "データ元", owner=owner), error_bars=_parse_error_bars(s["errorBars"], plot_type, owner), + marker=marker_shape, + alpha=_number(s["alpha"], "不透明度", default=1.0, minimum=0, maximum=1, owner=owner, field_name=f"{owner}不透明度"), + fill=fill, + ) + ) + return tuple(out) + + +def _position_text(value: Any, label: str, field_name: str) -> str: + """位置の入力(x / y / start / end)。文字列で持つ(数値は文字列にする)。解釈は dataprep。""" + if value is None: + return "" + if isinstance(value, bool): + raise UserError(f"「{label}」の値が不正です。", field=field_name) + if isinstance(value, (int, float)): + if isinstance(value, float) and not math.isfinite(value): + raise UserError(f"「{label}」の値が不正です。", field=field_name) + return repr(value) + if isinstance(value, str): + return value.strip() + raise UserError(f"「{label}」の値が不正です。", field=field_name) + + +def _parse_annotations(raw: Any, y2_used: bool) -> tuple[AnnotationSettings, ...]: + if raw is None: + return () + if not isinstance(raw, list): + raise UserError("「注釈」の値が不正です。", field="注釈") + if len(raw) > MAX_ANNOTATIONS: + raise UserError(f"注釈は{MAX_ANNOTATIONS}個までです。", field="注釈") + out = [] + used_ids: set[str] = set() + for i, given in enumerate(raw): + n = i + 1 + owner = f"注釈{n}の" + + def f(label: str) -> str: + return f"{owner}{label}" + + a = _merge(_DEFAULT_ANNOTATION, given) + aid = a["id"] if isinstance(a["id"], str) and a["id"] and a["id"] not in used_ids else f"a{n}" + while aid in used_ids: + aid += "_" + used_ids.add(aid) + kind = _choice(a["kind"], "種類", ANNOTATION_KINDS, owner=owner, field_name=f("種類")) + color = _string(a["color"], "色", owner=owner).strip() or _DEFAULT_ANNOTATION["color"] + if not is_color_like(color): + raise UserError(f"{owner}「色」が不正です。", field=f("色")) + alpha = _number(a["alpha"], "不透明度", default=None, minimum=0, maximum=1, owner=owner, field_name=f("不透明度")) + values: dict[str, Any] = {"id": aid, "kind": kind, "color": color, "alpha": alpha} + # 種類で使わない項目は検証せず、既定値にする(隠れた不正な値で描画を止めないため。§2.2) + if kind == "text": + text = _string(a["text"], "文字", owner=owner) + if len(text) > MAX_ANNOTATION_TEXT: + raise UserError(f"{owner}「文字」は{MAX_ANNOTATION_TEXT}文字以内で入力してください。", field=f("文字")) + coords = _choice(a["coords"], "座標", ANNOTATION_COORDS, owner=owner, field_name=f("座標")) + values.update( + text=text, + coords=coords, + x=_position_text(a["x"], "X", f"{owner} X"), + y=_position_text(a["y"], "Y", f"{owner} Y"), + font_size=_number(a["fontSize"], "文字の大きさ", default=None, exclusive_min=0, owner=owner, field_name=f("文字の大きさ")), + ) + else: + if kind == "vline": + values["x"] = _position_text(a["x"], "X", f"{owner} X") + elif kind == "hline": + values["y"] = _position_text(a["y"], "Y", f"{owner} Y") + else: + values["start"] = _position_text(a["start"], "開始", f("開始")) + values["end"] = _position_text(a["end"], "終了", f("終了")) + values["label"] = _string(a["label"], "凡例名", owner=owner).strip() + if kind in {"hline", "vline"}: + values["line_style"] = _choice(a["lineStyle"], "線種", LINE_STYLES, owner=owner, field_name=f("線種")) + values["line_width"] = _number( + a["lineWidth"], "線幅", default=1.0, exclusive_min=0, owner=owner, field_name=f("線幅") + ) + uses_y = kind in {"hline", "hspan"} or (kind == "text" and values.get("coords") == "data") + if uses_y and y2_used: + values["axis"] = _choice(a["axis"], "軸", ANNOTATION_AXES, owner=owner, field_name=f("軸")) + out.append(AnnotationSettings(**values)) + return tuple(out) + + +def _parse_fits(raw: Any, series_ids: set[str]) -> tuple[FitSettings, ...]: + if raw is None: + return () + if not isinstance(raw, list): + raise UserError("「近似曲線」の値が不正です。", field="近似曲線") + if len(raw) > MAX_FITS: + raise UserError(f"近似曲線は{MAX_FITS}本までです。", field="近似曲線") + out = [] + used_ids: set[str] = set() + for i, given in enumerate(raw): + n = i + 1 + owner = f"近似曲線{n}の" + f = _merge(_DEFAULT_FIT, given) + fid = f["id"] if isinstance(f["id"], str) and f["id"] and f["id"] not in used_ids else f"f{n}" + while fid in used_ids: + fid += "_" + used_ids.add(fid) + series = f["series"] + if not isinstance(series, str) or series not in series_ids: + raise UserError(f"{owner}系列が見つかりません。近似する系列を選び直してください。", field=f"{owner}系列") + model = _choice(f["model"], "モデル", FIT_MODELS, owner=owner, field_name=f"{owner}モデル") + degree = 1 + if model == "poly": + degree = _int_range(f["degree"], f"{owner}次数", 2, 6, default=2) + color = _string(f["color"], "色", owner=owner).strip() + if color and not is_color_like(color): + raise UserError(f"{owner}「色」が不正です。", field=f"{owner}色") + out.append( + FitSettings( + id=fid, + series=series, + model=model, + degree=degree, + show=_choice(f["show"], "式の表示先", FIT_SHOWS, owner=owner, field_name=f"{owner}式の表示先"), + color=color, + line_style=_choice(f["lineStyle"], "線種", LINE_STYLES, owner=owner, field_name=f"{owner}線種"), ) ) return tuple(out) @@ -752,8 +1000,12 @@ def parse_settings(raw: dict | None) -> Settings: if any(s.secondary_axis for s in series): check_axis_range(axes.y2, "第2Y") + annotations = _parse_annotations(raw.get("annotations"), any(s.secondary_axis for s in series)) + # 棒グラフでは近似曲線を使わない(隠れているので検証しない) + fits = () if plot.type == "bar" else _parse_fits(raw.get("fits"), {s.id for s in series}) + save = _parse_save(merged["save"]) - return Settings(version=SCHEMA_VERSION, load=load, plot=plot, axes=axes, series=series, save=save) + return Settings(version=SCHEMA_VERSION, load=load, plot=plot, axes=axes, series=series, save=save, annotations=annotations, fits=fits) def _figure_length(value: Any, label: str, default: float, unit: str) -> float: diff --git a/tests/unit/style_helpers.py b/tests/unit/style_helpers.py new file mode 100644 index 0000000..b204a32 --- /dev/null +++ b/tests/unit/style_helpers.py @@ -0,0 +1,82 @@ +"""Phase 5b のテスト(系列のスタイル・注釈・近似曲線)が共有する補助。""" +import contextlib + +import numpy as np +import pandas as pd + +from mplgui.codegen import generate_script +from mplgui.dataprep import plan_plot +from mplgui.loader import load_file +from mplgui.runner import figure_summary, run_script +from mplgui.settings import default_settings, parse_settings + +N = 10 + + +def frame(): + t = np.arange(N, dtype=float) + return pd.DataFrame( + { + "t": t, # 0 + "v": t * 2 + 10, # 1 + "lo": t * 2 + 8, # 2 + "hi": t * 2 + 13, # 3 + "w": 100 - t * 3.0, # 4 + } + ) + + +def series(y=1, x=0, **kw): + d = {"x": x if isinstance(x, str) else f"__idx__{x}", "y": f"__idx__{y}"} + d.update(kw) + return d + + +def raw_settings(series_list=None, plot_type="line", mutate=None, annotations=None, fits=None): + raw = default_settings() + raw["series"] = series_list if series_list is not None else [series()] + raw["plot"]["type"] = plot_type + if annotations is not None: + raw["annotations"] = annotations + if fits is not None: + raw["fits"] = fits + if mutate: + mutate(raw) + return raw + + +def plan_of(df=None, **kw): + loaded = load_file((df if df is not None else frame()).to_csv(index=False).encode("utf-8"), "d.csv", "", True) + settings = parse_settings(raw_settings(**kw)) + return plan_plot(loaded.df, settings) + + +class Built: + def __init__(self, tmp_path, df=None, **kw): + self.dir = tmp_path + (df if df is not None else frame()).to_csv(tmp_path / "d.csv", index=False, encoding="utf-8") + self.loaded = load_file((tmp_path / "d.csv").read_bytes(), "d.csv", "", True) + self.settings = parse_settings(raw_settings(**kw)) + self.plan = plan_plot(self.loaded.df, self.settings) + self.script = generate_script(self.settings, self.loaded.source, self.plan) + + @contextlib.contextmanager + def full(self): + with run_script(self.script.text, cwd=self.dir) as run: + yield run + + @contextlib.contextmanager + def auto(self): + with run_script(self.script.auto_render_text(), injected={"df": self.loaded.df}) as run: + yield run + + def check(self, fn): + """全体の実行と自動描画用の実行の両方に fn(fig) を適用し、要約が一致することも確かめる。要約を返す。""" + with self.full() as run: + fn(run.fig) + full = figure_summary(run.fig) + with self.auto() as run: + fn(run.fig) + auto = figure_summary(run.fig) + assert full == auto + return full diff --git a/tests/unit/test_annotations.py b/tests/unit/test_annotations.py new file mode 100644 index 0000000..be9dd64 --- /dev/null +++ b/tests/unit/test_annotations.py @@ -0,0 +1,312 @@ +"""Phase 5b: 注釈(G4)。dataprep の解釈・検査と、生成コードを CPython で実行した図を検査する。""" +import pandas as pd +import pytest + +from mplgui.errors import UserError +from mplgui.settings import MAX_ANNOTATIONS, default_annotation, parse_settings +from style_helpers import Built, frame, plan_of, raw_settings, series + +pytestmark = pytest.mark.unit + + +def ann(kind="hline", **kw): + d = {"kind": kind} + d.update(kw) + return d + + +def dates_frame(): + df = frame() + df["d"] = pd.date_range("2026-01-01", periods=len(df)).strftime("%Y-%m-%d") + return df + + +def text_frame(): + df = frame() + df["c"] = [f"k{i}" for i in range(len(df))] + return df + + +def build(tmp_path, annotations, df=None, **kw): + return Built(tmp_path, df=df, annotations=annotations, **kw) + + +# ---------------------------------------------------------------- 設定 + + +def test_default_annotation_shape(): + d = default_annotation() + assert d["kind"] == "hline" and d["coords"] == "data" and d["alpha"] is None and d["fontSize"] is None + assert parse_settings(raw_settings(annotations=[d])).annotations[0].kind == "hline" + + +def test_missing_keys_filled_and_numbers_become_strings(): + s = parse_settings(raw_settings(annotations=[{"kind": "text", "x": 1.5, "y": 2, "text": "a"}])).annotations[0] + assert (s.x, s.y, s.color, s.coords) == ("1.5", "2", "#000000", "data") + + +def test_limit_of_50(): + parse_settings(raw_settings(annotations=[ann(y=1)] * MAX_ANNOTATIONS)) + with pytest.raises(UserError) as e: + parse_settings(raw_settings(annotations=[ann(y=1)] * (MAX_ANNOTATIONS + 1))) + assert str(e.value) == "注釈は50個までです。" + + +def test_unused_fields_are_not_validated(): + # hline は text / coords / fontSize / start / end / x を使わない + s = parse_settings( + raw_settings(annotations=[ann("hline", y=1, text="x" * 500, coords="zzz", fontSize="abc", start=object(), x=[1])]) + ) + assert s.annotations[0].kind == "hline" + + +def test_used_fields_are_validated(): + bad = [ + (ann("text", text="x" * 201, x=1, y=1), "注釈1の文字"), + (ann("text", text="a", coords="zzz"), "注釈1の座標"), + (ann("text", text="a", fontSize=0), "注釈1の文字の大きさ"), + (ann("hline", y=1, lineWidth=0), "注釈1の線幅"), + (ann("hline", y=1, lineStyle="zzz"), "注釈1の線種"), + (ann("hline", y=1, color="notacolor"), "注釈1の色"), + (ann("hspan", start=1, end=2, alpha=2), "注釈1の不透明度"), + (ann("zzz"), "注釈1の種類"), + ] + for item, field_name in bad: + with pytest.raises(UserError) as e: + parse_settings(raw_settings(annotations=[item])) + assert e.value.field == field_name, item + + +def test_axis_only_validated_when_secondary_is_used(): + parse_settings(raw_settings(annotations=[ann(y=1, axis="zzz")])) + with pytest.raises(UserError): + parse_settings(raw_settings([series(secondaryAxis=True)], annotations=[ann(y=1, axis="zzz")])) + # Y を使わない種類は、第2Y軸を使っていても検証しない + parse_settings(raw_settings([series(secondaryAxis=True)], annotations=[ann("vline", x=1, axis="zzz")])) + + +# ---------------------------------------------------------------- 描画計画(検査) + + +@pytest.mark.parametrize( + "item, field_name", + [ + (ann("hline"), "注釈1のY"), + (ann("hline", y="abc"), "注釈1のY"), + (ann("vline"), "注釈1のX"), + (ann("vline", x="2026-01-01"), "注釈1のX"), # 数値の X に日付 + (ann("hspan", start=1), "注釈1の終了"), + (ann("vspan", end=1), "注釈1の開始"), + (ann("text", text=" ", x=1, y=1), "注釈1の文字"), + (ann("text", text="a", y=1), "注釈1のX"), + (ann("text", text="a", x=1), "注釈1のY"), + (ann("text", text="a", x=1, y="1,5"), "注釈1のY"), + ], +) +def test_input_errors(item, field_name): + with pytest.raises(UserError) as e: + plan_of(annotations=[item]) + assert e.value.field == field_name + + +def test_datetime_x_errors(): + for item, field_name in [(ann("vline", x="1.5"), "注釈1のX"), (ann("vspan", start="2026-01-01", end="zzz"), "注釈1の終了")]: + with pytest.raises(UserError) as e: + plan_of(df=dates_frame(), series_list=[series(x=5)], annotations=[item]) + assert e.value.field == field_name and "日時" in str(e.value) + + +def test_log_axis_rejects_non_positive(): + def log_y(raw): + raw["axes"]["y"]["scale"] = "log" + + with pytest.raises(UserError) as e: + plan_of(annotations=[ann("hline", y=0)], mutate=log_y) + assert e.value.field == "注釈1のY" + with pytest.raises(UserError): + plan_of(annotations=[ann("hspan", start=-1, end=3)], mutate=log_y) + + def log_x(raw): + raw["axes"]["x"]["scale"] = "log" + + with pytest.raises(UserError): + plan_of(df=frame().assign(t=lambda d: d["t"] + 1), annotations=[ann("vline", x=0)], mutate=log_x) + # 図の中の割合は軸の種類に関係しない + plan_of(annotations=[ann("text", text="a", coords="axes", x=0, y=0)], mutate=log_y) + + +def test_plan_values_by_axis_kind(): + p = plan_of(annotations=[ann("vline", x="2.5"), ann("hline", y="1e1")]).annotations + assert (p[0].x, p[0].date, p[1].y) == (2.5, False, 10.0) + p = plan_of(df=dates_frame(), series_list=[series(x=5)], annotations=[ann("vline", x="2026/01/03 12:00"), ann("vspan", start="2026-01-02", end="2026-01-04")]).annotations + assert p[0].x == "2026-01-03 12:00:00" and p[0].date and (p[1].start, p[1].end) == ("2026-01-02", "2026-01-04") + p = plan_of(df=text_frame(), series_list=[series(x=5)], annotations=[ann("vline", x="1.5")]).annotations + assert p[0].x == 1.5 and not p[0].date + + +def test_hidden_secondary_axis_falls_back_to_ax(): + # 第2軸の系列に描ける点が無いと ax2 は作られない + df = frame().assign(w=float("nan")) + p = plan_of(df=df, series_list=[series(1), series(4, secondaryAxis=True)], annotations=[ann(y=1, axis="y2")]) + assert p.annotations[0].target == "ax" + + +def test_tick_estimate_includes_annotations(): + def step(raw): + raw["axes"]["y"]["majorStep"] = 0.5 + + plan_of(annotations=[ann(y=20)], mutate=step) + with pytest.raises(UserError): + plan_of(annotations=[ann(y=2000)], mutate=step) + + +# ---------------------------------------------------------------- 生成コードの図 + + +def test_no_annotation_section_by_default(tmp_path): + b = Built(tmp_path) + assert "注釈" not in b.script.text and "# ==== 5. 軸" in b.script.text + + +def test_section_numbers_shift(tmp_path): + b = build(tmp_path, [ann(y=15)]) + heads = [ln for ln in b.script.text.splitlines() if ln.startswith("# ==== ")] + assert [h.split(" ")[2] for h in heads] == ["1.", "2.", "3.", "4.", "5.", "6.", "7.", "8.", "9."] + assert heads[4] == "# ==== 5. 注釈 ====" and heads[5].startswith("# ==== 6. 軸") + + +def test_hline_vline(tmp_path): + b = build(tmp_path, [ann("hline", y=15, label="基準値", color="#FF0000", lineWidth=2), ann("vline", x=4, alpha=0.5)]) + assert 'ax.axhline(15.0, color="#FF0000", linewidth=2.0, linestyle="dashed", label="基準値")' in b.script.text + assert 'ax.axvline(4.0, color="#000000", linewidth=1.0, linestyle="dashed", alpha=0.5)' in b.script.text + + def check(fig): + ax = fig.axes[0] + h = [ln for ln in ax.lines if ln.get_label() == "基準値"][0] + assert list(h.get_ydata()) == [15.0, 15.0] and h.get_color() == "#FF0000" and h.get_linewidth() == 2.0 + assert "基準値" in [t.get_text() for t in ax.get_legend().get_texts()] + + summary = b.check(check) + assert summary[0]["annotations"] == {"texts": 0, "hlines": 1, "vlines": 1, "hspans": 0, "vspans": 0} + + +def test_spans(tmp_path): + b = build(tmp_path, [ann("hspan", start=20, end=12, label="帯"), ann("vspan", start=2, end=3, alpha=0.4)]) + assert "ax.axhspan(20.0, 12.0, color=\"#000000\", alpha=0.2, linewidth=0, label=\"帯\")" in b.script.text + assert "ax.axvspan(2.0, 3.0, color=\"#000000\", alpha=0.4, linewidth=0)" in b.script.text + + def check(fig): + ax = fig.axes[0] + spans = [p for p in ax.patches] + assert len(spans) == 2 and {round(p.get_alpha(), 2) for p in spans} == {0.2, 0.4} + + summary = b.check(check) + assert summary[0]["annotations"]["hspans"] == 1 and summary[0]["annotations"]["vspans"] == 1 + + +def test_text_data_and_axes(tmp_path): + b = build( + tmp_path, + [ann("text", text="ピーク", x=3, y=16, fontSize=9), ann("text", text="左上", coords="axes", x=0.05, y=0.95, alpha=0.5)], + ) + assert 'ax.text(3.0, 16.0, "ピーク", color="#000000", fontsize=9.0)' in b.script.text + assert 'ax.text(0.05, 0.95, "左上", transform=ax.transAxes, color="#000000", fontsize=FONT_SIZE, alpha=0.5)' in b.script.text + + def check(fig): + texts = fig.axes[0].texts + assert [t.get_text() for t in texts] == ["ピーク", "左上"] + assert texts[0].get_position() == (3.0, 16.0) and texts[1].get_position() == (0.05, 0.95) + assert texts[0].get_fontsize() == 9.0 + + summary = b.check(check) + assert summary[0]["annotations"]["texts"] == 2 + + +def test_datetime_x(tmp_path): + b = build( + tmp_path, + [ann("vline", x="2026-01-04"), ann("vspan", start="2026-01-06", end="2026-01-08 12:00"), ann("text", text="t", x="2026-01-02", y=15)], + df=dates_frame(), + series_list=[series(x=5)], + ) + assert 'ax.axvline(pd.Timestamp("2026-01-04"), ' in b.script.text + assert 'pd.Timestamp("2026-01-08 12:00:00")' in b.script.text + summary = b.check(lambda fig: None) + assert summary[0]["annotations"]["vlines"] == 1 and summary[0]["annotations"]["vspans"] == 1 + + +def test_text_x_position_is_category_index(tmp_path): + b = build(tmp_path, [ann("vline", x=1.5)], df=text_frame(), series_list=[series(x=5)]) + + def check(fig): + line = [ln for ln in fig.axes[0].lines if ln.get_label().startswith("_child")][0] + assert list(line.get_xdata()) == [1.5, 1.5] + + b.check(check) + + +def test_bar_annotations(tmp_path): + b = build(tmp_path, [ann("hline", y=20), ann("vline", x=2)], plot_type="bar") + summary = b.check(lambda fig: None) + assert summary[0]["annotations"]["hlines"] == 1 and summary[0]["annotations"]["vlines"] == 1 + assert summary[0]["patches"] == 10 # 棒だけ(線は patches に入らない) + + +def test_secondary_axis_annotations(tmp_path): + b = build( + tmp_path, + [ann("hline", y=50, axis="y2", label="第2"), ann("hspan", start=60, end=70, axis="y2"), ann("text", text="r", x=2, y=80, axis="y2"), ann("hline", y=15)], + series_list=[series(1), series(4, secondaryAxis=True)], + ) + assert "ax2.axhline(50.0" in b.script.text and "ax2.axhspan" in b.script.text and "ax2.text(2.0" in b.script.text + assert "ax.axhline(15.0" in b.script.text + + def check(fig): + ax, ax2 = fig.axes + assert len(ax2.texts) == 1 and not ax.texts + assert "第2" in [t.get_text() for t in ax.get_legend().get_texts()] # まとめて凡例にする + + b.check(check) + + +def test_legend_with_only_annotation_label(tmp_path): + b = build(tmp_path, [ann(y=15, label="基準")], series_list=[series(label="_hidden")]) + assert "凡例に出せるラベルが無い" not in b.script.text + + def check(fig): + assert [t.get_text() for t in fig.axes[0].get_legend().get_texts()] == ["基準"] + + b.check(check) + + +def test_no_label_no_legend_still_holds(tmp_path): + b = build(tmp_path, [ann(y=15)], series_list=[series(label="_hidden")]) + assert "凡例に出せるラベルが無い" in b.script.text + + +def test_annotations_do_not_change_existing_series_summary(tmp_path): + base = Built(tmp_path).check(lambda fig: None)[0] + with_ann = build(tmp_path, [ann(y=15, label="x"), ann("vspan", start=1, end=2)]).check(lambda fig: None)[0] + for key in ("title", "xlabel", "ylabel", "errorbars", "collections", "markers", "alphas", "bands", "fitlines"): + assert base[key] == with_ann[key], key + + +def test_injection(tmp_path): + evil = 'a"\n__import__("os").system("x") # \'\'\'' + b = build(tmp_path, [ann("text", text=evil, x=1, y=1), ann(y=2, label=evil), ann("vline", x=1, label="\\")]) + compile(b.script.text, "plot.py", "exec") + assert "\n__import__" not in b.script.text + with b.full() as run: + assert evil in [t.get_text() for t in run.fig.axes[0].texts] + assert evil in [t.get_text() for t in run.fig.axes[0].get_legend().get_texts()] + + +def test_date_text_cannot_inject(): + with pytest.raises(UserError): + plan_of(df=dates_frame(), series_list=[series(x=5)], annotations=[ann("vline", x='2026-01-01"); __import__("os")#')]) + + +def test_steps_registered(tmp_path): + b = build(tmp_path, [ann(y=15), ann("vline", x=2)]) + fields = [s.field for s in b.script.steps] + assert "注釈1" in fields and "注釈2" in fields diff --git a/tests/unit/test_defaults_parity.py b/tests/unit/test_defaults_parity.py index fcfc227..ef866f5 100644 --- a/tests/unit/test_defaults_parity.py +++ b/tests/unit/test_defaults_parity.py @@ -6,7 +6,7 @@ import pytest -from mplgui.settings import default_settings +from mplgui.settings import default_annotation, default_fit, default_settings pytestmark = pytest.mark.unit @@ -30,3 +30,17 @@ def test_js_palette_has_default_series_color(tmp_path): out = subprocess.run(["node", "--input-type=module", "-e", script], capture_output=True, text=True, check=True, timeout=30) palette, color = json.loads(out.stdout) assert len(palette) == 11 and palette[0] == color == default_settings()["series"][0]["color"] + + +@pytest.mark.skipif(shutil.which("node") is None, reason="node が無い") +def test_js_and_python_element_defaults_match(tmp_path): + module = tmp_path / "defaults.mjs" + module.write_text((REPO / "js" / "defaults.js").read_text(encoding="utf-8"), encoding="utf-8") + script = ( + f"import {{ DEFAULT_ANNOTATION, DEFAULT_FIT }} from {json.dumps(module.as_uri())}; " + "console.log(JSON.stringify([DEFAULT_ANNOTATION, DEFAULT_FIT]));" + ) + out = subprocess.run(["node", "--input-type=module", "-e", script], capture_output=True, text=True, check=True, timeout=30) + annotation, fit = json.loads(out.stdout) + assert annotation == default_annotation() + assert fit == default_fit() diff --git a/tests/unit/test_fits.py b/tests/unit/test_fits.py new file mode 100644 index 0000000..0ec64f3 --- /dev/null +++ b/tests/unit/test_fits.py @@ -0,0 +1,311 @@ +"""Phase 5b: 近似曲線(G5)。係数・R² を numpy の直接計算と比べ、式の文字・表示先・エラーを検査する。""" +import numpy as np +import pandas as pd +import pytest + +from mplgui.codegen import POLY_TEXT_FUNCTION +from mplgui.errors import UserError +from mplgui.settings import MAX_FITS, default_fit, parse_settings +from style_helpers import N, Built, frame, plan_of, raw_settings, series + +pytestmark = pytest.mark.unit + + +def fit(**kw): + d = {"series": "s1"} + d.update(kw) + return d + + +def quad_frame(): + t = np.arange(N, dtype=float) + return pd.DataFrame({"t": t, "q": 0.5 * t**2 - 2 * t + 3 + np.sin(t) * 0.1, "w": 100 - 3 * t}) + + +def fit_line(ax): + return [ln for ln in ax.lines if "$R^2$" in ln.get_label() or ln.get_label() == "_fit"][0] + + +def poly_text(coef): + ns: dict = {} + exec("\n".join(POLY_TEXT_FUNCTION), ns) + return ns["poly_text"](coef) + + +def r_squared(x, y, deg): + p = np.polyfit(x, y, deg) + resid = y - np.polyval(p, x) + return p, 1 - np.sum(resid**2) / np.sum((y - y.mean()) ** 2) + + +# ---------------------------------------------------------------- poly_text + + +def test_poly_text_formats(): + assert poly_text([3.21, -0.5, 1.234]) == "y = 1.234x$^{2}$ - 0.5x + 3.21" + assert poly_text([-1.0, 2.0]) == "y = 2x - 1" + assert poly_text([5.0, -2.0]) == "y = -2x + 5" + assert poly_text([0.0, 1.0, 0.0, -1.0]) == "y = -1x$^{3}$ + 0x$^{2}$ + 1x + 0" + assert poly_text([1.23456789, 9.87654321]) == "y = 9.877x + 1.235" + assert poly_text([1e-5, 1e6]) == "y = 1e+06x + 1e-05" + + +# ---------------------------------------------------------------- 設定 + + +def test_default_fit_and_validation(): + assert default_fit()["model"] == "linear" + s = parse_settings(raw_settings(fits=[fit(), fit(model="poly", degree=4, color="#112233")])).fits + assert (s[0].degree, s[1].degree, s[1].color, s[0].line_style, s[0].show) == (1, 4, "#112233", "dashed", "legend") + + +def test_limit_of_20(): + parse_settings(raw_settings(fits=[fit()] * MAX_FITS)) + with pytest.raises(UserError): + parse_settings(raw_settings(fits=[fit()] * (MAX_FITS + 1))) + + +@pytest.mark.parametrize( + "item, field_name", + [ + ({"series": "nope"}, "近似曲線1の系列"), + (fit(model="zzz"), "近似曲線1のモデル"), + (fit(model="poly", degree=1), "近似曲線1の次数"), + (fit(model="poly", degree=7), "近似曲線1の次数"), + (fit(model="poly", degree=2.5), "近似曲線1の次数"), + (fit(show="zzz"), "近似曲線1の式の表示先"), + (fit(color="notacolor"), "近似曲線1の色"), + (fit(lineStyle="zzz"), "近似曲線1の線種"), + ], +) +def test_validation_errors(item, field_name): + with pytest.raises(UserError) as e: + parse_settings(raw_settings(fits=[item])) + assert e.value.field == field_name + + +def test_degree_hidden_for_linear(): + s = parse_settings(raw_settings(fits=[fit(model="linear", degree="abc")])).fits[0] + assert s.degree == 1 + + +def test_bar_fits_are_not_validated_or_used(tmp_path): + b = Built(tmp_path, plot_type="bar", fits=[{"series": "nope", "model": "zzz"}]) + assert not b.settings.fits and not b.plan.fits and "np.polynomial" not in b.script.text + + +# ---------------------------------------------------------------- 計算 + +def test_linear_fit_matches_numpy(tmp_path): + b = Built(tmp_path, df=quad_frame(), series_list=[series(1)], fits=[fit()]) + assert "np.polynomial.Polynomial.fit(x[ok], y[ok], 1).convert()" in b.script.text + df = quad_frame() + coef_np, r2_np = r_squared(df["t"].to_numpy(), df["q"].to_numpy(), 1) + + def check(fig): + line = fit_line(fig.axes[0]) + assert len(line.get_xdata()) == 200 + assert line.get_xdata()[0] == df["t"].min() and line.get_xdata()[-1] == df["t"].max() + np.testing.assert_allclose(line.get_ydata(), np.polyval(coef_np, line.get_xdata()), atol=1e-8) + assert line.get_label() == f"{b.plan.series[0].legend_label}の近似: {poly_text(coef_np[::-1])}($R^2$ = {r2_np:.4f})" + + b.check(check) + + +@pytest.mark.parametrize("degree", [2, 3, 6]) +def test_poly_fit_matches_numpy(tmp_path, degree): + df = quad_frame() + b = Built(tmp_path, df=df, series_list=[series(1)], fits=[fit(model="poly", degree=degree)]) + coef_np, r2_np = r_squared(df["t"].to_numpy(), df["q"].to_numpy(), degree) + + def check(fig): + line = fit_line(fig.axes[0]) + np.testing.assert_allclose(line.get_ydata(), np.polyval(coef_np, line.get_xdata()), rtol=1e-6, atol=1e-6) + assert line.get_label().endswith(f"($R^2$ = {r2_np:.4f})") + assert f"x$^{{{degree}}}$" in line.get_label() + + b.check(check) + + +def test_fit_with_large_x_values_is_stable(tmp_path): + t = np.arange(N, dtype=float) + 1e9 + df = pd.DataFrame({"t": t, "v": 2 * (t - 1e9) + 5}) + b = Built(tmp_path, df=df, series_list=[series(1)], fits=[fit()]) + + def check(fig): + line = fit_line(fig.axes[0]) + np.testing.assert_allclose(line.get_ydata()[[0, -1]], [5.0, 2 * (N - 1) + 5.0], atol=1e-4) + + b.check(check) + + +def test_fit_uses_only_plotted_rows(tmp_path): + df = quad_frame() + df.loc[2, "q"] = np.nan + b = Built(tmp_path, df=df, series_list=[series(1)], fits=[fit()]) + ok = df["q"].notna() + coef_np, _ = r_squared(df["t"][ok].to_numpy(), df["q"][ok].to_numpy(), 1) + b.check(lambda fig: np.testing.assert_allclose(fit_line(fig.axes[0]).get_ydata()[[0, -1]], np.polyval(coef_np, [0.0, N - 1.0]), atol=1e-8)) + + +def test_scatter_fit(tmp_path): + b = Built(tmp_path, df=quad_frame(), series_list=[series(1)], plot_type="scatter", fits=[fit()]) + summary = b.check(lambda fig: None) + assert summary[0]["fitlines"] == 1 and summary[0]["collections"] == 1 + + +# ---------------------------------------------------------------- 表示先と見た目 + + +def test_show_legend(tmp_path): + b = Built(tmp_path, df=quad_frame(), series_list=[series(1, label="温度")], fits=[fit()]) + + def check(fig): + labels = [t.get_text() for t in fig.axes[0].get_legend().get_texts()] + assert labels[0] == "温度" and labels[1].startswith("温度の近似: y = ") + + summary = b.check(check) + assert summary[0]["fitlines"] == 1 and summary[0]["fittexts"] == 0 + assert "def poly_text(coef):" in b.script.text + assert b.script.text.index("def poly_text") < b.script.text.index("# ==== 1. データの読み込み") + + +def test_show_text_stacks_in_order(tmp_path): + b = Built( + tmp_path, + df=quad_frame(), + series_list=[series(1, label="A"), series(2, label="B")], + fits=[fit(show="text"), fit(show="none"), {"series": "s2", "show": "text"}], + ) + assert "ax.text(0.03, 0.97," in b.script.text and "ax.text(0.03, 0.9," in b.script.text + + def check(fig): + ax = fig.axes[0] + texts = ax.texts + assert len(texts) == 2 and texts[0].get_position() == (0.03, 0.97) and texts[1].get_position() == (0.03, 0.9) + assert texts[0].get_text().startswith("Aの近似: y = ") and texts[1].get_text().startswith("Bの近似: y = ") + assert texts[0].get_color() == "#FF4B00" + legend = [t.get_text() for t in ax.get_legend().get_texts()] + assert legend == ["A", "B"] # 図の中・出さない、は凡例に出ない + + summary = b.check(check) + assert summary[0]["fitlines"] == 3 and summary[0]["fittexts"] == 2 and summary[0]["annotations"]["texts"] == 0 + + +def test_show_none_has_no_poly_text_function(tmp_path): + b = Built(tmp_path, df=quad_frame(), fits=[fit(show="none")]) + assert "poly_text" not in b.script.text + summary = b.check(lambda fig: None) + assert summary[0]["fitlines"] == 1 + + +def test_color_and_style(tmp_path): + b = Built(tmp_path, df=quad_frame(), series_list=[series(1, lineWidth=3, color="#005AFF")], fits=[fit(lineStyle="dotted"), fit(color="#00FF00")]) + + def check(fig): + lines = [ln for ln in fig.axes[0].lines if "$R^2$" in ln.get_label()] + assert lines[0].get_color() == "#005AFF" and lines[0].get_linestyle() == ":" and lines[0].get_linewidth() == 3.0 + assert lines[1].get_color() == "#00FF00" + + b.check(check) + + +def test_secondary_axis_fit(tmp_path): + b = Built(tmp_path, df=quad_frame(), series_list=[series(1), series(2, secondaryAxis=True)], fits=[{"series": "s2", "show": "text"}]) + assert "ax2.plot(x_fit" in b.script.text and "ax2.text(0.03, 0.97" in b.script.text + + def check(fig): + ax, ax2 = fig.axes + assert len(ax2.texts) == 1 and not ax.texts + assert sum("$R^2$" in t for t in [ln.get_label() for ln in ax.lines]) == 0 + + b.check(check) + + +def test_fit_is_drawn_right_after_its_series(tmp_path): + b = Built(tmp_path, df=quad_frame(), series_list=[series(1), series(2)], fits=[fit()]) + text = b.script.text + assert text.index("# 系列2") > text.index("# 近似曲線1") > text.index("# 系列1") + + +def test_default_x_is_row_number(tmp_path): + b = Built(tmp_path, df=quad_frame(), series_list=[series(1, x="")], fits=[fit()]) + b.check(lambda fig: None) + + +def test_log_axis_fit_is_linear(tmp_path): + def log_y(raw): + raw["axes"]["y"]["scale"] = "log" + + b = Built(tmp_path, df=pd.DataFrame({"t": np.arange(5.0), "v": np.arange(5.0) * 3 + 1}), fits=[fit()], mutate=log_y) + b.check(lambda fig: None) + + +# ---------------------------------------------------------------- エラー + + +def test_datetime_x_error(): + df = quad_frame().assign(d=pd.date_range("2026-01-01", periods=N).strftime("%Y-%m-%d")) + with pytest.raises(UserError) as e: + plan_of(df=df, series_list=[series(1, x=3)], fits=[fit()]) + assert e.value.field == "近似曲線1の系列" and "日時" in str(e.value) + + +def test_text_x_error(): + df = quad_frame().assign(c=[f"k{i}" for i in range(N)]) + with pytest.raises(UserError) as e: + plan_of(df=df, series_list=[series(1, x=3)], fits=[fit()]) + assert e.value.field == "近似曲線1の系列" and "文字列" in str(e.value) + + +def test_not_enough_distinct_x(): + df = pd.DataFrame({"t": [1.0, 1.0, 2.0, 2.0], "v": [1.0, 2.0, 3.0, 4.0]}) + plan_of(df=df, fits=[fit()]) + with pytest.raises(UserError) as e: + plan_of(df=df, fits=[fit(model="poly", degree=2)]) + assert e.value.field == "近似曲線1の系列" and "3個以上" in str(e.value) + + +def test_not_enough_points_after_dropping_missing(): + df = pd.DataFrame({"t": [1.0, 2.0, 3.0], "v": [1.0, np.nan, np.nan]}) + with pytest.raises(UserError): + plan_of(df=df, fits=[fit()]) + + +def test_constant_y_error(): + df = pd.DataFrame({"t": np.arange(5.0), "v": np.full(5, 3.0)}) + with pytest.raises(UserError) as e: + plan_of(df=df, fits=[fit()]) + assert "すべて同じ" in str(e.value) + + +def test_series_without_points_error(): + df = pd.DataFrame({"t": np.arange(5.0), "v": np.arange(5.0), "w": np.nan}) + with pytest.raises(UserError) as e: + plan_of(df=df, series_list=[series(1), series(2)], fits=[{"series": "s2"}]) + assert e.value.field == "近似曲線1の系列" + + +# ---------------------------------------------------------------- 安全性 + + +def test_series_name_cannot_inject(tmp_path): + evil = 'x"\n__import__("os").system("x") # \'\'\'' + b = Built(tmp_path, df=quad_frame(), series_list=[series(1, label=evil)], fits=[fit(), fit(show="text")]) + compile(b.script.text, "plot.py", "exec") + assert "\n__import__" not in b.script.text + with b.full() as run: + labels = [ln.get_label() for ln in run.fig.axes[0].lines] + assert any(label.startswith(evil + "の近似: ") for label in labels) + + +def test_column_name_comment_cannot_inject(tmp_path): + df = quad_frame().rename(columns={"q": 'q"\n__import__("os")'}) + b = Built(tmp_path, df=df, series_list=[series(1)], fits=[fit()]) + compile(b.script.text, "plot.py", "exec") + assert "\n__import__" not in b.script.text + + +def test_uses_only_numpy_in_generated_code(tmp_path): + b = Built(tmp_path, df=quad_frame(), fits=[fit()]) + assert "polyfit" not in b.script.text and "scipy" not in b.script.text diff --git a/tests/unit/test_runner.py b/tests/unit/test_runner.py index 7db8b69..e92833a 100644 --- a/tests/unit/test_runner.py +++ b/tests/unit/test_runner.py @@ -471,3 +471,18 @@ def test_raster_pixels_truncates_like_agg(): assert raster_pixels(8, 6, 300) == (2400, 1800) assert raster_pixels(3.3333, 2, 100) == (333, 200) # 切り捨て(Agg は int(width)) + + +def test_figure_summary_has_5b_keys_with_neutral_defaults(): + from mplgui.runner import figure_summary + + fig, ax = plt.subplots() + ax.plot([0, 1], [0, 1], label="a") + try: + summary = figure_summary(fig)[0] + finally: + plt.close(fig) + assert summary["bands"] == 0 and summary["fitlines"] == 0 and summary["fittexts"] == 0 + assert summary["annotations"] == {"texts": 0, "hlines": 0, "vlines": 0, "hspans": 0, "vspans": 0} + assert summary["markers"] == ["None"] and summary["alphas"] == [None] + assert summary["lines"] == 1 and summary["errorbars"] == 0 diff --git a/tests/unit/test_series_style.py b/tests/unit/test_series_style.py new file mode 100644 index 0000000..caeac4f --- /dev/null +++ b/tests/unit/test_series_style.py @@ -0,0 +1,260 @@ +"""Phase 5b: 系列のスタイル(G3)。点の形・不透明度・塗りつぶし帯。生成コードを CPython で実行した図を検査する。""" +import numpy as np +import pandas as pd +import pytest + +from mplgui.errors import UserError +from mplgui.settings import parse_settings +from style_helpers import Built, frame, plan_of, raw_settings, series + +pytestmark = pytest.mark.unit + + +def fill(lower=2, upper=3, alpha=None): + d = {"lower": f"__idx__{lower}", "upper": f"__idx__{upper}"} + if alpha is not None: + d["alpha"] = alpha + return d + + +def series_line(ax): + return [ln for ln in ax.lines if not ln.get_label().startswith("_")][0] + + +# ---------------------------------------------------------------- 点の形 + + +def test_line_auto_marker_keeps_phase4_behavior(): + assert plan_of().series[0].marker == "" + p = plan_of(series_list=[series(markerSize=16)]).series[0] + assert p.marker == "o" and p.marker_size == 16.0 + + +def test_line_shape_without_size_uses_scatter_default_area(): + p = plan_of(series_list=[series(marker="s")]).series[0] + assert p.marker == "s" and p.marker_size == 24.0 + + +def test_line_shape_with_size_keeps_size(): + p = plan_of(series_list=[series(marker="^", markerSize=9)]).series[0] + assert p.marker == "^" and p.marker_size == 9.0 + + +def test_line_none_ignores_marker_size(): + p = plan_of(series_list=[series(marker="none", markerSize=30)]).series[0] + assert p.marker == "" + + +def test_scatter_marker_plan(): + assert plan_of(series_list=[series()], plot_type="scatter").series[0].marker == "" + p = plan_of(series_list=[series(marker="D")], plot_type="scatter").series[0] + assert p.marker == "D" and p.marker_size == 24.0 + + +def test_line_shape_draws_marker(tmp_path): + b = Built(tmp_path, series_list=[series(marker="s")]) + assert 'marker="s", markersize=24.0 ** 0.5' in b.script.text + + def check(fig): + line = series_line(fig.axes[0]) + assert line.get_marker() == "s" and line.get_markersize() == pytest.approx(24.0**0.5) + + summary = b.check(check) + assert summary[0]["markers"] == ["s"] + + +def test_line_none_draws_no_marker(tmp_path): + b = Built(tmp_path, series_list=[series(marker="none", markerSize=30)]) + assert "marker=" not in b.script.text.split("# ==== 4.")[1].split("# ==== 5.")[0] + summary = b.check(lambda fig: None) + assert summary[0]["markers"] == ["None"] + + +def test_scatter_shape_changes_marker_path(tmp_path): + circle = Built(tmp_path, series_list=[series()], plot_type="scatter") + square = Built(tmp_path, series_list=[series(marker="s")], plot_type="scatter") + assert 'marker="s"' in square.script.text and "marker=" not in circle.script.text.split("# ==== 4.")[1].split("# ==== 5.")[0] + with circle.full() as a, square.full() as b: + pa = a.fig.axes[0].collections[0].get_paths()[0] + pb = b.fig.axes[0].collections[0].get_paths()[0] + assert len(pa.vertices) != len(pb.vertices) + square.check(lambda fig: None) + + +def test_scatter_none_is_error(): + with pytest.raises(UserError) as e: + parse_settings(raw_settings([series(marker="none")], "scatter")) + assert e.value.field == "系列1の点の形" + + +def test_marker_choice_validated(): + with pytest.raises(UserError) as e: + parse_settings(raw_settings([series(marker="zzz")])) + assert e.value.field == "系列1の点の形" + + +# ---------------------------------------------------------------- 不透明度 + + +def test_alpha_default_writes_nothing(tmp_path): + b = Built(tmp_path) + assert "alpha=" not in b.script.text.split("# ==== 4.")[1].split("# ==== 5.")[0] + + +@pytest.mark.parametrize("plot_type", ["line", "scatter", "bar"]) +def test_alpha_is_applied(tmp_path, plot_type): + b = Built(tmp_path, series_list=[series(alpha=0.5)], plot_type=plot_type) + assert "alpha=0.5" in b.script.text + + def check(fig): + ax = fig.axes[0] + if plot_type == "line": + assert series_line(ax).get_alpha() == 0.5 + elif plot_type == "scatter": + assert ax.collections[0].get_alpha() == 0.5 + else: + assert all(p.get_alpha() == 0.5 for p in ax.patches) + + b.check(check) + + +def test_alpha_multi_bar(tmp_path): + b = Built(tmp_path, series_list=[series(1, alpha=0.4), series(4)], plot_type="bar") + with b.full() as run: + patches = run.fig.axes[0].patches + assert {p.get_alpha() for p in patches[: len(patches) // 2]} == {0.4} + assert {p.get_alpha() for p in patches[len(patches) // 2 :]} == {None} + b.check(lambda fig: None) + + +@pytest.mark.parametrize("value", [-0.1, 1.5, "abc"]) +def test_alpha_validated(value): + with pytest.raises(UserError) as e: + parse_settings(raw_settings([series(alpha=value)])) + assert e.value.field == "系列1の不透明度" + + +def test_alpha_summary(tmp_path): + summary = Built(tmp_path, series_list=[series(alpha=0.3)]).check(lambda fig: None) + assert summary[0]["alphas"] == [0.3] + + +# ---------------------------------------------------------------- 塗りつぶし帯 + + +def test_no_band_by_default(): + assert plan_of().series[0].fill is None + + +def test_band_plan_resolves_columns(): + p = plan_of(series_list=[series(fill=fill(alpha=0.4))]).series[0] + assert (p.fill.lower_index, p.fill.upper_index, p.fill.alpha) == (2, 3, 0.4) + assert p.fill.lower_label == "lo [2]" + + +def test_band_is_drawn_before_series(tmp_path): + b = Built(tmp_path, series_list=[series(fill=fill())]) + text = b.script.text + assert text.index("fill_between") < text.index("ax.plot(x[ok]") + assert 'label="_fill"' in text and "alpha=0.25, linewidth=0" in text + + def check(fig): + ax = fig.axes[0] + poly = [c for c in ax.collections if c.get_label() == "_fill"] + assert len(poly) == 1 + ys = poly[0].get_paths()[0].vertices[:, 1] + assert ys.min() == pytest.approx(8.0) and ys.max() == pytest.approx(31.0) + assert poly[0].get_alpha() == 0.25 + assert "_fill" not in [t.get_text() for t in ax.get_legend().get_texts()] + + summary = b.check(check) + assert summary[0]["bands"] == 1 + + +def test_band_scatter_and_secondary_axis(tmp_path): + b = Built(tmp_path, series_list=[series(fill=fill(), secondaryAxis=True)], plot_type="scatter") + assert "ax2.fill_between" in b.script.text + b.check(lambda fig: None) + + +def test_band_missing_values_break_the_band_and_warn(tmp_path): + df = frame().astype({"lo": object}) + df.loc[3, "lo"] = "x" + df.loc[4, "lo"] = np.nan + b = Built(tmp_path, df=df, series_list=[series(fill=fill())]) + warnings = [w["message"] for w in b.plan.warnings] + assert len(warnings) == 1 and "塗りつぶし帯(下端)" in warnings[0] and "1件" in warnings[0] and '"x"' in warnings[0] + b.check(lambda fig: None) + + +def test_band_warning_counts_only_plotted_rows(tmp_path): + df = frame().astype({"lo": object}) + df.loc[3, "lo"] = "x" + df.loc[3, "v"] = np.nan # この行は描かない + b = Built(tmp_path, df=df, series_list=[series(fill=fill())]) + assert not b.plan.warnings + + +def test_band_warning_has_thousands_hint(): + df = frame().astype({"lo": object}) + df.loc[3, "lo"] = "1,234" + p = plan_of(df=df, series_list=[series(fill=fill())]) + assert "桁区切り" in p.warnings[0]["message"] + + +def test_band_column_out_of_range(): + with pytest.raises(UserError) as e: + plan_of(series_list=[series(fill=fill(lower=9))]) + assert e.value.field == "系列1の塗りつぶし帯" + + +def test_band_one_side_empty_is_error(): + with pytest.raises(UserError) as e: + parse_settings(raw_settings([series(fill={"lower": "__idx__2", "upper": ""})])) + assert e.value.field == "系列1の塗りつぶし帯" + + +def test_band_datetime_x(tmp_path): + df = frame() + df["d"] = pd.date_range("2026-01-01", periods=len(df)).strftime("%Y-%m-%d") + b = Built(tmp_path, df=df, series_list=[series(x=5, fill=fill())]) + assert b.plan.series[0].datetime_x + b.check(lambda fig: None) + + +def test_band_text_x(tmp_path): + df = frame() + df["c"] = [f"k{i}" for i in range(len(df))] + b = Built(tmp_path, df=df, series_list=[series(x=5, fill=fill())]) + assert b.plan.series[0].categorical_x + b.check(lambda fig: None) + + +def test_band_extents_feed_tick_estimate(): + # 帯の上端(最大 37)まで範囲に入るので、間隔 0.1 だと 100 本を超える。帯が無ければ v の最大 28 でも超える点は同じだが、見積もりが帯を含むこと + from mplgui.dataprep import MAX_MAJOR_TICKS + + def mutate(raw): + raw["axes"]["y"]["majorStep"] = 0.36 + + ok = plan_of(series_list=[series()], mutate=mutate) # (28-10)*1.1/0.36+1 = 56 + assert ok.axes.y.major_step == 0.36 + with pytest.raises(UserError): + plan_of(df=frame().assign(hi=lambda d: d["hi"] * 20), series_list=[series(fill=fill())], mutate=mutate) + assert MAX_MAJOR_TICKS == 100 + + +def test_bar_ignores_marker_and_fill(tmp_path): + # 棒グラフでは点の形・帯は隠れているので、不正な値でも検証せず、使わない + s = series(marker="zzz", fill={"lower": "oops", "upper": ""}, alpha=0.5) + b = Built(tmp_path, series_list=[s], plot_type="bar") + assert "fill_between" not in b.script.text and "marker" not in b.script.text + assert "alpha=0.5" in b.script.text + + +def test_band_label_with_injection(tmp_path): + df = frame().rename(columns={"lo": 'x"\n__import__("os")'}) + b = Built(tmp_path, df=df, series_list=[series(fill=fill())]) + compile(b.script.text, "plot.py", "exec") + assert "\n__import__" not in b.script.text + b.check(lambda fig: None) diff --git a/tests/unit/test_settings.py b/tests/unit/test_settings.py index 10d0c49..5f4cb4c 100644 --- a/tests/unit/test_settings.py +++ b/tests/unit/test_settings.py @@ -20,7 +20,7 @@ def test_defaults_are_complete_and_parse(): d = default_settings() assert d["version"] == SCHEMA_VERSION == 4 - assert set(d) == {"version", "load", "plot", "axes", "series", "save"} + assert set(d) == {"version", "load", "plot", "axes", "series", "annotations", "fits", "save"} assert set(d["axes"]) == {"x", "y", "y2"} s = parse_settings(d) assert s.plot.type == "line" and s.plot.font_size == 15 and s.plot.figure.width == 8 and s.plot.figure.height == 6 @@ -787,3 +787,80 @@ def test_migrate_v3_to_v4_and_older(): for bad in (5, 0, "4"): with pytest.raises(UserError): migrate_settings({"version": bad}) + + +# ---------------------------------------------------------------- Phase 5b: 系列のスタイル・注釈・近似曲線 + + +def test_5b_defaults(): + d = default_settings() + assert d["annotations"] == [] and d["fits"] == [] + assert d["series"][0]["marker"] == "auto" and d["series"][0]["alpha"] == 1 + assert d["series"][0]["fill"] == {"lower": "", "upper": "", "alpha": 0.25} + s = parse_settings(d) + assert s.annotations == () and s.fits == () + assert (s.series[0].marker, s.series[0].alpha, s.series[0].fill.enabled, s.series[0].fill.alpha) == ("auto", 1.0, False, 0.25) + + +def test_v3_settings_without_5b_keys_parse_with_defaults(): + s = parse_settings({"version": 3, "series": [{"y": "__idx__1"}]}) + assert s.series[0].marker == "auto" and s.annotations == () and s.fits == () + + +def test_series_style_fields_are_validated_with_series_number(): + base = default_settings() + + def with_series(**kw): + raw = copy.deepcopy(base) + raw["series"] = [{"id": "s1"}, {"id": "s2", **kw}] + return raw + + for kw, field_name in [ + ({"marker": "zzz"}, "系列2の点の形"), + ({"alpha": 1.1}, "系列2の不透明度"), + ({"alpha": -0.1}, "系列2の不透明度"), + ({"fill": {"lower": "__idx__1", "upper": ""}}, "系列2の塗りつぶし帯"), + ({"fill": {"lower": "", "upper": "__idx__1"}}, "系列2の塗りつぶし帯"), + ({"fill": {"lower": "abc", "upper": "__idx__1"}}, "系列2の塗りつぶし帯"), + ({"fill": {"lower": "__idx__1", "upper": "__idx__2", "alpha": 2}}, "系列2の塗りつぶし帯"), + ]: + with pytest.raises(UserError) as e: + parse_settings(with_series(**kw)) + assert e.value.field == field_name, kw + + +def test_fill_alpha_is_hidden_when_no_band(): + s = parse_settings({"series": [{"fill": {"lower": "", "upper": "", "alpha": "oops"}}]}) + assert not s.series[0].fill.enabled + + +def test_scatter_marker_none_is_error_but_line_is_fine(): + parse_settings({"plot": {"type": "line"}, "series": [{"marker": "none"}]}) + with pytest.raises(UserError) as e: + parse_settings({"plot": {"type": "scatter"}, "series": [{"marker": "none"}]}) + assert e.value.field == "系列1の点の形" + + +def test_bar_hides_marker_and_fill_but_keeps_alpha(): + s = parse_settings( + {"plot": {"type": "bar"}, "series": [{"marker": "zzz", "fill": {"lower": "x", "upper": ""}, "alpha": 0.4}]} + ).series[0] + assert (s.marker, s.fill.enabled, s.alpha) == ("auto", False, 0.4) + + +def test_annotation_and_fit_elements_are_filled_from_defaults(): + s = parse_settings({"annotations": [{}], "fits": [{}]}) + a, f = s.annotations[0], s.fits[0] + assert (a.id, a.kind, a.color, a.line_style, a.line_width, a.alpha, a.font_size) == ("a1", "hline", "#000000", "dashed", 1.0, None, None) + assert (f.id, f.series, f.model, f.degree, f.show, f.color) == ("f1", "s1", "linear", 1, "legend", "") + + +def test_annotation_and_fit_lists_must_be_lists(): + for key in ("annotations", "fits"): + with pytest.raises(UserError): + parse_settings({key: {}}) + + +def test_annotation_ids_are_made_unique(): + s = parse_settings({"annotations": [{"id": "a1", "y": 1}, {"id": "a1", "y": 2}, {"y": 3}]}) + assert len({a.id for a in s.annotations}) == 3 From cf78b4c92225b00b1cdcfc2a10e658bef0d7c798 Mon Sep 17 00:00:00 2001 From: mioupa <79833278+mioupa@users.noreply.github.com> Date: Tue, 10 Nov 2026 17:40:31 +0900 Subject: [PATCH 3/6] Add the analysis section and series-card style, reorder and duplicate controls (Phase 5b) Co-Authored-By: Claude Opus 5.5 --- css/style.css | 51 +++++- index.html | 23 +++ js/bridge.js | 5 + js/main.js | 12 +- js/state.js | 93 +++++++++- js/ui/annotations.js | 236 ++++++++++++++++++++++++++ js/ui/colorPicker.js | 23 ++- js/ui/fits.js | 178 +++++++++++++++++++ js/ui/series.js | 125 +++++++++++++- tests/e2e/helpers.py | 69 ++++++++ tests/e2e/test_annotations.py | 154 +++++++++++++++++ tests/e2e/test_codegen_consistency.py | 107 +++++++++++- tests/e2e/test_fits.py | 98 +++++++++++ tests/e2e/test_panel_sections.py | 1 + tests/e2e/test_series_style.py | 141 +++++++++++++++ tests/fixtures/README.md | 1 + tests/fixtures/band.csv | 13 ++ tests/fixtures/make_fixtures.py | 12 ++ tests/unit/test_js_modules.py | 67 ++++++++ 19 files changed, 1390 insertions(+), 19 deletions(-) create mode 100644 js/ui/annotations.js create mode 100644 js/ui/fits.js create mode 100644 tests/e2e/test_annotations.py create mode 100644 tests/e2e/test_fits.py create mode 100644 tests/e2e/test_series_style.py create mode 100644 tests/fixtures/band.csv diff --git a/css/style.css b/css/style.css index 27d4c03..12765d4 100644 --- a/css/style.css +++ b/css/style.css @@ -1121,7 +1121,8 @@ button.series-color-chip.active { } /* 系列カードの「エラーバー」の折りたたみ(目盛の折りたたみと同じ控えめな見た目) */ -.series-errorbars { +.series-errorbars, +.series-fill { margin: 8px 0 0; border-left: 2px solid var(--line-soft); padding-left: 8px; @@ -1151,7 +1152,8 @@ button.series-color-chip.active { transform: rotate(-45deg); transition: transform 0.12s ease; } -.series-errorbars[open] > .series-errorbars-summary::before { +.series-errorbars[open] > .series-errorbars-summary::before, +.series-fill[open] > .series-errorbars-summary::before { transform: rotate(45deg); } .series-errorbars-summary:hover { @@ -1186,3 +1188,48 @@ button.series-color-chip.active { grid-template-columns: 1fr; } } + +/* 系列カードの操作ボタン(↑ ↓ 複製 削除)と、注釈・近似曲線のカード */ +.series-item-actions { + display: flex; + flex-wrap: wrap; + justify-content: flex-end; + gap: 4px; +} +.series-item-actions button.small-btn { + padding: 5px 8px; +} +.series-item-actions button:disabled { + opacity: 0.5; + cursor: not-allowed; +} +.series-fill[hidden], +.series-marker-wrap[hidden], +.ann-field[hidden], +.ann-help[hidden], +.fit-degree-wrap[hidden], +.fit-color-picker-wrap[hidden], +#fitList[hidden], +#addFitBtn[hidden], +#fitBarNote[hidden] { + display: none; +} +.annotation-item .row > div, +.fit-item .row > div { + min-width: 0; +} +.annotation-item input, +.annotation-item select, +.fit-item input, +.fit-item select { + min-width: 0; + max-width: 100%; +} +.fit-color-picker-wrap { + margin-top: 6px; +} +#addAnnotationBtn:disabled, +#addFitBtn:disabled { + opacity: 0.5; + cursor: not-allowed; +} diff --git a/index.html b/index.html index b2f4c78..5a58a72 100644 --- a/index.html +++ b/index.html @@ -544,6 +544,29 @@

Matplotlib GUI

+
+ 注釈・解析 +
+
+
+ 注釈 + +
+
+
文字・水平線・垂直線・帯(横・縦)を図に加えます。位置は軸の種類に合わせて入力します(日時の X は日付、文字列の X は何番目か)。
+
+
+
+ 近似曲線 + +
+
+ +
系列の点から、最小二乗法で1次式・多項式をあてはめます(X が数値の系列だけ)。対数軸でも、近似は軸の目盛ではなく元の値で行うので、曲線は曲がって見えます。
+
+
+
+
保存
diff --git a/js/bridge.js b/js/bridge.js index a3959fd..44452b6 100644 --- a/js/bridge.js +++ b/js/bridge.js @@ -358,6 +358,11 @@ const scheduleScriptRefresh = () => { scriptTimer = window.setTimeout(refreshScript, SCRIPT_REFRESH_DELAY_MS); }; +// 画面の操作の注意(系列の帯の列を戻した、など)を、次の描画結果に1度だけ添える +export const addNote = (message) => { + notes = [...notes, message]; +}; + // ---- 読込(複数ファイル: D6)---- const files = () => getSettings().load.files; const fileLabel = (id) => { diff --git a/js/main.js b/js/main.js index c8a7d95..ca84bc5 100644 --- a/js/main.js +++ b/js/main.js @@ -11,7 +11,9 @@ import { bindLoadSection } from "./ui/loadSection.js"; import { bindSaveSection } from "./ui/saveSection.js"; import { bindDateFormat } from "./ui/dateFormat.js"; import { bindClipboard } from "./ui/clipboard.js"; -import { bindSeriesEvents, refreshSources, renderSeriesList, syncMarkerSizeDisplay, syncVisibility } from "./ui/series.js"; +import { addVisibilityHook, bindSeriesEvents, refreshSources, renderSeriesList, syncMarkerSizeDisplay, syncVisibility } from "./ui/series.js"; +import { bindAnnotations, renderAnnotationList, syncAnnotations } from "./ui/annotations.js"; +import { bindFits, renderFitList, syncFits } from "./ui/fits.js"; import { bindStyleSection } from "./ui/styleSection.js"; import { initPanelSections } from "./ui/panelSections.js"; import { bindTabs } from "./ui/tabs.js"; @@ -36,6 +38,10 @@ initPanelSections(); bindTabs(); bindForms(); bindSeriesEvents(); +addVisibilityHook(syncAnnotations); +addVisibilityHook(syncFits); +bindAnnotations(); +bindFits(); bindSaveFormatEvents(); bindLoadSection(); bindDropPaste(); @@ -50,6 +56,10 @@ bindStyleSection(); subscribe((_settings, change) => { if (change.kind === "series-list") { renderSeriesList(); + } else if (change.kind === "annotation-list") { + renderAnnotationList(); + } else if (change.kind === "fit-list") { + renderFitList(); } else if (change.kind === "path" && change.path === "plot.palette") { renderSeriesList(); // 色の選択肢と各系列の色を、新しいパレットで描き直す } else { diff --git a/js/state.js b/js/state.js index c7ebfea..7672166 100644 --- a/js/state.js +++ b/js/state.js @@ -1,6 +1,6 @@ // 設定オブジェクト(単一の正)。画面の入力はすべてここへ書き込み、描画・読込はここから JSON を作る。 // DOM には触れない。変更は subscribe で購読する。 -import { DEFAULT_SERIES, DEFAULT_SETTINGS } from "./defaults.js"; +import { DEFAULT_ANNOTATION, DEFAULT_FIT, DEFAULT_SERIES, DEFAULT_SETTINGS } from "./defaults.js"; import { getPalette, paletteColor } from "./palettes.js"; import { newSeriesDefaults } from "./presets.js"; @@ -9,6 +9,8 @@ const clone = (value) => JSON.parse(JSON.stringify(value)); let settings = clone(DEFAULT_SETTINGS); let lastPreset = null; // 最後に適用したスタイルプリセット(このセッションの間だけ。設定オブジェクトには入れない) let seriesCounter = 1; // 系列 id は連番で払い出し、削除しても再利用しない +let annotationCounter = 0; // 注釈 id(a1, a2, ...)。削除しても再利用しない +let fitCounter = 0; // 近似曲線 id(f1, f2, ...)。削除しても再利用しない const listeners = new Set(); export const getSettings = () => settings; @@ -98,12 +100,97 @@ export const addSeries = (overrides = {}) => { return series; }; +// 系列を削除する。その系列の近似曲線も消す(消した近似曲線の数を返す。系列が1つだけなら削除せず -1) export const removeSeries = (id) => { - if (settings.series.length <= 1) return; + if (settings.series.length <= 1) return -1; const idx = settings.series.findIndex((s) => s.id === id); - if (idx < 0) return; + if (idx < 0) return -1; settings.series.splice(idx, 1); + const before = settings.fits.length; + settings.fits = settings.fits.filter((f) => f.series !== id); + const removedFits = before - settings.fits.length; + notify({ kind: "series-list", origin: "user" }); + if (removedFits > 0) notify({ kind: "fit-list", origin: "user" }); + return removedFits; +}; + +// 系列を delta(-1 で前、+1 で後ろ)だけ動かす。端では何もしない +export const moveSeries = (id, delta) => { + const idx = settings.series.findIndex((s) => s.id === id); + const to = idx + delta; + if (idx < 0 || to < 0 || to >= settings.series.length) return; + const [item] = settings.series.splice(idx, 1); + settings.series.splice(to, 0, item); notify({ kind: "series-list", origin: "user" }); }; +// 系列の複製: すべての設定を写し、id は新しく、色は現在のパレットの未使用の色にして、元の系列の直後に入れる(近似曲線は写さない) +export const duplicateSeries = (id) => { + const idx = settings.series.findIndex((s) => s.id === id); + if (idx < 0) return null; + seriesCounter += 1; + const copy = { ...clone(settings.series[idx]), id: `s${seriesCounter}`, color: nextSeriesColor() }; + settings.series.splice(idx + 1, 0, copy); + notify({ kind: "series-list", origin: "user" }); + return copy; +}; + +// ---- 注釈・近似曲線 ---- +export const addAnnotation = () => { + annotationCounter += 1; + const item = { ...clone(DEFAULT_ANNOTATION), id: `a${annotationCounter}` }; + settings.annotations.push(item); + notify({ kind: "annotation-list", origin: "user" }); + return item; +}; + +export const updateAnnotation = (id, patch, origin = "user") => { + const item = settings.annotations.find((a) => a.id === id); + if (!item) return; + let changed = false; + for (const [key, value] of Object.entries(patch)) { + if (item[key] !== value) { + item[key] = value; + changed = true; + } + } + if (changed) notify({ kind: "annotation-field", id, fields: Object.keys(patch), origin }); +}; + +export const removeAnnotation = (id) => { + const idx = settings.annotations.findIndex((a) => a.id === id); + if (idx < 0) return; + settings.annotations.splice(idx, 1); + notify({ kind: "annotation-list", origin: "user" }); +}; + +export const addFit = () => { + fitCounter += 1; + const first = settings.series[0]; + const item = { ...clone(DEFAULT_FIT), id: `f${fitCounter}`, series: first ? first.id : DEFAULT_FIT.series }; + settings.fits.push(item); + notify({ kind: "fit-list", origin: "user" }); + return item; +}; + +export const updateFit = (id, patch, origin = "user") => { + const item = settings.fits.find((f) => f.id === id); + if (!item) return; + let changed = false; + for (const [key, value] of Object.entries(patch)) { + if (item[key] !== value) { + item[key] = value; + changed = true; + } + } + if (changed) notify({ kind: "fit-field", id, fields: Object.keys(patch), origin }); +}; + +export const removeFit = (id) => { + const idx = settings.fits.findIndex((f) => f.id === id); + if (idx < 0) return; + settings.fits.splice(idx, 1); + notify({ kind: "fit-list", origin: "user" }); +}; + export const hasSecondaryAxis = () => settings.series.some((s) => s.secondaryAxis); diff --git a/js/ui/annotations.js b/js/ui/annotations.js new file mode 100644 index 0000000..37fef6e --- /dev/null +++ b/js/ui/annotations.js @@ -0,0 +1,236 @@ +// 注釈(文字・水平線・垂直線・横の帯・縦の帯)のカード。カードは state の annotations から描く。 +// 入力欄の出し分けは Python(settings / dataprep)と同じ規則: 使わない項目は隠し、値は残す(要件 §2.2)。 +import { addAnnotation, getSettings, hasSecondaryAxis, removeAnnotation, updateAnnotation } from "../state.js"; +import { bindSeriesColorControls, colorPickerHtml } from "./colorPicker.js"; +import { readNumber } from "./forms.js"; +import { xAxisKind } from "./series.js"; + +const esc = (text) => + String(text ?? "").replace(/&/g, "&").replace(//g, ">").replace(/"/g, """); + +const KINDS = [ + ["text", "文字"], + ["hline", "水平線"], + ["vline", "垂直線"], + ["hspan", "横の帯(Yの範囲)"], + ["vspan", "縦の帯(Xの範囲)"], +]; + +// 要素 id の末尾 → 設定のキー(種別: text / number) +const FIELD_KEYS = { + kind: ["kind", "text"], + text: ["text", "text"], + coords: ["coords", "text"], + x: ["x", "text"], + y: ["y", "text"], + start: ["start", "text"], + end: ["end", "text"], + axis: ["axis", "text"], + "line-style": ["lineStyle", "text"], + "line-width": ["lineWidth", "number"], + alpha: ["alpha", "number"], + "font-size": ["fontSize", "number"], + label: ["label", "text"], +}; + +const X_EXAMPLE = { + number: "例 1.5", + log: "例 1.5", + datetime: "例 2026-01-31 12:00", + category: "何番目か(0 始まり)", +}; +const X_HELP = { + number: "X 軸の値(数)です。", + log: "X 軸の値(数)です。対数軸では 0 より大きい値にしてください。", + datetime: "年が先頭の日付・日時です(例 2026-01-31 12:00)。", + category: "何番目のカテゴリか(0 始まりの数)です。1.5 なら 2 つ目と 3 つ目の間です。", +}; + +const cardHtml = (a, index) => { + const id = (name) => `annotation-${a.id}-${name}`; + const text = (name, label, extra = "") => ` +
+ + + +
`; + return ` +
+
注釈 ${index + 1}
+ +
+
+ + +
+
+ + +
+
+ + +
+ ${text("x", "X")} + ${text("y", "Y")} + ${text("start", "開始")} + ${text("end", "終了")} +
+ + +
+
+
+ + ${colorPickerHtml(id("color"), a.color)} +
+
+ + +
+
+
+
+ + +
+
+ + +
+
+
+ + +
+
+ + +
`; +}; + +const buildCard = (a, index) => { + const item = document.createElement("div"); + item.className = "series-item annotation-item"; + item.id = `annotation-${a.id}`; + item.dataset.annId = a.id; + item.innerHTML = cardHtml(a, index); + item.querySelector(`#annotation-${a.id}-kind`).value = a.kind; + item.querySelector(`#annotation-${a.id}-coords`).value = a.coords; + item.querySelector(`#annotation-${a.id}-axis`).value = a.axis; + item.querySelector(`#annotation-${a.id}-line-style`).value = a.lineStyle; + bindSeriesColorControls(item, (color) => updateAnnotation(a.id, { color })); + item.querySelector(`#annotation-${a.id}-remove`).addEventListener("click", () => removeAnnotation(a.id)); + return item; +}; + +// 種類ごとの表示(Python の使う項目と同じ) +const SHOWN = { + text: ["text", "coords", "x", "y", "font-size"], + hline: ["y", "line", "label"], + vline: ["x", "line", "label"], + hspan: ["start", "end", "label"], + vspan: ["start", "end", "label"], +}; + +const syncCard = (item, a, xKind, hasY2) => { + const shown = new Set(SHOWN[a.kind] || []); + shown.add("alpha"); + const dataY = a.kind === "hline" || a.kind === "hspan" || (a.kind === "text" && a.coords === "data"); + if (hasY2 && dataY) shown.add("axis"); + for (const el of item.querySelectorAll(".ann-field")) el.hidden = !shown.has(el.dataset.annField); + const id = (name) => `annotation-${a.id}-${name}`; + const label = (name, text) => { + const el = item.querySelector(`label[for="${id(name)}"]`); + if (el) el.textContent = text; + }; + const note = (name, example, help) => { + const input = item.querySelector(`#${id(name)}`); + input.placeholder = example; + const helpEl = input.closest(".ann-field").querySelector(".ann-help"); + helpEl.textContent = help; + helpEl.hidden = !help; + }; + const axesCoords = a.kind === "text" && a.coords === "axes"; + const yExample = ["例 1.5", "Y 軸の値(数)です。"]; + if (a.kind === "text") { + label("x", "X"); + label("y", "Y"); + if (axesCoords) { + note("x", "0〜1", "図の左端が 0、右端が 1 です。"); + note("y", "0〜1", "図の下端が 0、上端が 1 です。"); + } else { + note("x", X_EXAMPLE[xKind], X_HELP[xKind]); + note("y", ...yExample); + } + } else if (a.kind === "hline") { + label("y", "Y"); + note("y", ...yExample); + } else if (a.kind === "vline") { + label("x", "X"); + note("x", X_EXAMPLE[xKind], X_HELP[xKind]); + } else if (a.kind === "hspan") { + label("start", "開始(Y)"); + label("end", "終了(Y)"); + note("start", ...yExample); + note("end", ...yExample); + } else if (a.kind === "vspan") { + label("start", "開始(X)"); + label("end", "終了(X)"); + note("start", X_EXAMPLE[xKind], X_HELP[xKind]); + note("end", X_EXAMPLE[xKind], X_HELP[xKind]); + } +}; + +// 表示の同期(入力中の欄を作り直さない。系列・軸・データの変更のたびに呼ぶ) +export const syncAnnotations = () => { + const { annotations } = getSettings(); + const xKind = xAxisKind(); + const hasY2 = hasSecondaryAxis(); + for (const item of document.querySelectorAll("#annotationList .annotation-item")) { + const a = annotations.find((x) => x.id === item.dataset.annId); + if (a) syncCard(item, a, xKind, hasY2); + } +}; + +export const renderAnnotationList = () => { + const list = document.getElementById("annotationList"); + if (!list) return; + const { annotations } = getSettings(); + list.replaceChildren(...annotations.map((a, i) => buildCard(a, i))); + syncAnnotations(); +}; + +const onInput = (event) => { + const target = event.target; + if (!target || !target.matches || !target.matches("input, select")) return; + const item = target.closest(".annotation-item"); + if (!item) return; + const name = target.id.replace(`annotation-${item.dataset.annId}-`, ""); + const entry = FIELD_KEYS[name]; + if (!entry) return; + const [key, kind] = entry; + updateAnnotation(item.dataset.annId, { [key]: kind === "number" ? readNumber(target) : target.value }); +}; + +export const bindAnnotations = () => { + const list = document.getElementById("annotationList"); + const add = document.getElementById("addAnnotationBtn"); + if (add) add.addEventListener("click", () => addAnnotation()); + if (list) { + list.addEventListener("input", onInput); + list.addEventListener("change", onInput); + } + renderAnnotationList(); +}; diff --git a/js/ui/colorPicker.js b/js/ui/colorPicker.js index 73682db..9c671a5 100644 --- a/js/ui/colorPicker.js +++ b/js/ui/colorPicker.js @@ -4,10 +4,23 @@ import { getSettings } from "../state.js"; const normalizeColor = (value) => String(value || "").trim().toUpperCase(); +// 色の選択UIのマークアップ(系列カード以外の注釈・近似曲線カードでも使う。bindSeriesColorControls で結ぶ)。idBase は trigger の id に使う +export const colorPickerHtml = (idBase, color, extraClass = "") => ` +
+ + +
+
${String(color).replace(/[<>&"]/g, "")}
`; + const closeAllColorPanels = (exceptPanel = null) => { - const seriesList = document.getElementById("seriesList"); - if (!seriesList) return; - for (const p of seriesList.querySelectorAll(".series-color-panel")) { + for (const p of document.querySelectorAll(".series-color-panel")) { if (exceptPanel && p === exceptPanel) continue; p.classList.add("hidden"); } @@ -78,11 +91,9 @@ export const bindSeriesColorControls = (item, onChange) => { // パネル外クリックでオーバーレイを閉じる export const bindColorPanelOutsideClick = () => { document.addEventListener("click", (event) => { - const seriesList = document.getElementById("seriesList"); - if (!seriesList) return; const target = event.target; if (target && target.closest(".series-color-picker")) return; - for (const panel of seriesList.querySelectorAll(".series-color-panel")) { + for (const panel of document.querySelectorAll(".series-color-panel")) { panel.classList.add("hidden"); } }); diff --git a/js/ui/fits.js b/js/ui/fits.js new file mode 100644 index 0000000..7042c64 --- /dev/null +++ b/js/ui/fits.js @@ -0,0 +1,178 @@ +// 近似曲線のカード。カードは state の fits から描く。系列の選択肢は系列の変更のたびに同期する。 +import { addFit, getSettings, removeFit, updateFit } from "../state.js"; +import { bindSeriesColorControls, colorPickerHtml } from "./colorPicker.js"; +import { readNumber } from "./forms.js"; +import { seriesDisplayName } from "./series.js"; + +const MAX_FITS = 20; +const esc = (text) => + String(text ?? "").replace(/&/g, "&").replace(//g, ">").replace(/"/g, """); + +const seriesOptions = () => + getSettings().series.map((s, i) => { + const name = seriesDisplayName(s); + return { value: s.id, label: name ? `系列${i + 1}(${name})` : `系列${i + 1}` }; + }); + +const fillSeriesSelect = (select, selected) => { + const options = seriesOptions(); + select.innerHTML = ""; + for (const opt of options) { + const o = document.createElement("option"); + o.value = opt.value; + o.textContent = opt.label; + select.appendChild(o); + } + select.value = options.some((o) => o.value === selected) ? selected : ""; +}; + +const cardHtml = (f, index) => { + const id = (name) => `fit-${f.id}-${name}`; + return ` +
+
近似曲線 ${index + 1}
+ +
+
+ + +
+
+
+ + +
+
+ + +
+
+
+ + +
+
+
+ + +
${colorPickerHtml(id("color-picker"), f.color || "#000000")}
+
+
+ + +
+
`; +}; + +const seriesColorOf = (seriesId) => { + const s = getSettings().series.find((x) => x.id === seriesId); + return s ? s.color : "#000000"; +}; + +const buildCard = (f, index) => { + const item = document.createElement("div"); + item.className = "series-item fit-item"; + item.id = `fit-${f.id}`; + item.dataset.fitId = f.id; + item.innerHTML = cardHtml(f, index); + const get = (name) => item.querySelector(`#fit-${f.id}-${name}`); + fillSeriesSelect(get("series"), f.series); + get("series").dataset.options = JSON.stringify(seriesOptions()); + get("model").value = f.model; + get("show").value = f.show; + get("line-style").value = f.lineStyle; + get("color").value = f.color ? "custom" : ""; + // 色を選ぶときの初めの色: 系列の色(設定の color は選んだ時点で書く) + const picker = item.querySelector(".series-color"); + if (!f.color) picker.value = seriesColorOf(f.series); + bindSeriesColorControls(item, (color) => updateFit(f.id, { color })); + get("remove").addEventListener("click", () => removeFit(f.id)); + return item; +}; + +const syncCard = (item, f) => { + item.querySelector(".fit-degree-wrap").hidden = f.model !== "poly"; + item.querySelector(".fit-color-picker-wrap").hidden = !f.color; + // 系列の選択肢(系列の追加・削除・並べ替え・名前の変更に追従する) + const select = item.querySelector(`#fit-${f.id}-series`); + const options = JSON.stringify(seriesOptions()); + if (select.dataset.options !== options) { + fillSeriesSelect(select, f.series); + select.dataset.options = options; + } +}; + +export const syncFits = () => { + const { fits, plot } = getSettings(); + const isBar = plot.type === "bar"; + const list = document.getElementById("fitList"); + const add = document.getElementById("addFitBtn"); + const note = document.getElementById("fitBarNote"); + if (list) list.hidden = isBar; + if (add) { + add.hidden = isBar; + add.disabled = fits.length >= MAX_FITS; + } + if (note) note.hidden = !isBar; + const addAnn = document.getElementById("addAnnotationBtn"); + if (addAnn) addAnn.disabled = getSettings().annotations.length >= 50; + for (const item of document.querySelectorAll("#fitList .fit-item")) { + const f = fits.find((x) => x.id === item.dataset.fitId); + if (f) syncCard(item, f); + } +}; + +export const renderFitList = () => { + const list = document.getElementById("fitList"); + if (!list) return; + list.replaceChildren(...getSettings().fits.map((f, i) => buildCard(f, i))); + syncFits(); +}; + +const onInput = (event) => { + const target = event.target; + if (!target || !target.matches || !target.matches("input, select")) return; + const item = target.closest(".fit-item"); + if (!item) return; + const id = item.dataset.fitId; + const name = target.id.replace(`fit-${id}-`, ""); + if (name === "series") updateFit(id, { series: target.value }); + else if (name === "model") updateFit(id, { model: target.value }); + else if (name === "degree") updateFit(id, { degree: readNumber(target) }); + else if (name === "show") updateFit(id, { show: target.value }); + else if (name === "line-style") updateFit(id, { lineStyle: target.value }); + else if (name === "color") { + if (target.value === "") updateFit(id, { color: "" }); + else { + const f = getSettings().fits.find((x) => x.id === id); + const current = item.querySelector(".series-color").value; + updateFit(id, { color: current || (f ? seriesColorOf(f.series) : "#000000") }); + } + } +}; + +export const bindFits = () => { + const list = document.getElementById("fitList"); + const add = document.getElementById("addFitBtn"); + if (add) add.addEventListener("click", () => addFit()); + if (list) { + list.addEventListener("input", onInput); + list.addEventListener("change", onInput); + } + renderFitList(); +}; diff --git a/js/ui/series.js b/js/ui/series.js index 4133dbe..603f0b1 100644 --- a/js/ui/series.js +++ b/js/ui/series.js @@ -1,5 +1,6 @@ // 系列カード(追加・削除・列セレクト・種別/第2軸に応じた表示切替)。カードは state の系列リストから描く。 -import { addSeries, getSettings, hasSecondaryAxis, removeSeries, updateSeries, setPath } from "../state.js"; +import { addSeries, duplicateSeries, getSettings, hasSecondaryAxis, moveSeries, removeSeries, updateSeries, setPath } from "../state.js"; +import { addNote } from "../bridge.js"; import { bindSeriesColorControls } from "./colorPicker.js"; import { syncAxisTicks } from "./axisTicks.js"; import { readNumber } from "./forms.js"; @@ -39,6 +40,17 @@ export const xAxisKind = () => { return numeric; }; +// 系列の表示名(凡例名があればそれ、無ければ Y 列の表示)。近似曲線の系列の選択肢に使う +export const seriesDisplayName = (series) => { + if (series.label) return series.label; + const col = columnsOf(series).find((c) => c.value === series.y); + return col ? col.label : ""; +}; + +// 画面の同期(syncVisibility)の最後に呼ぶ関数を足す(注釈・近似曲線のカード。series.js から循環して import しないため) +const visibilityHooks = []; +export const addVisibilityHook = (fn) => visibilityHooks.push(fn); + const esc = (text) => String(text).replace(/&/g, "&").replace(//g, ">").replace(/"/g, """); @@ -114,7 +126,12 @@ const cardHtml = (series, plotType) => { return `
系列
- +
+ + + + +
@@ -166,6 +183,27 @@ const cardHtml = (series, plotType) => {
+
+
+ + +
+
+ + +
+
@@ -187,9 +225,35 @@ const cardHtml = (series, plotType) => {
+
+ 塗りつぶし帯 +
+
下端と上端の列の間を塗ります(値そのもの。誤差の大きさではありません)。
+
+
+ + +
+
+ + +
+
+
+ + +
+
+
`; }; +// 塗りつぶし帯の折りたたみの開閉(エラーバーと同じ。系列 id ごとにセッション中だけ覚える) +const openFill = new Map(); +const usesFill = (series) => !!series.fill && !!(series.fill.lower || series.fill.upper); +const fillOpen = (series) => (openFill.has(series.id) ? openFill.get(series.id) : usesFill(series)); +const fillColumnOptions = (columns) => [{ value: "", label: "(なし)" }, ...columns]; + const errorColumnOptions = (columns) => [{ value: "", label: "(列を選択)" }, ...columns]; // エラーバーの入力欄に設定の値を入れる(カードを作るとき) @@ -252,12 +316,27 @@ const buildCard = (series, plotType) => { item.querySelector(".series-source-wrap").hidden = !hasManySources(); item.querySelector(".series-line-style").value = series.lineStyle; fillErrorControls(item, series, columns); + item.querySelector(".series-marker").value = series.marker; + fillSelect(item.querySelector('[data-fill="lower"]'), fillColumnOptions(columns), series.fill.lower); + fillSelect(item.querySelector('[data-fill="upper"]'), fillColumnOptions(columns), series.fill.upper); + item.querySelector('[data-fill="alpha"]').value = series.fill.alpha === null ? "" : String(series.fill.alpha); const details = item.querySelector(".series-errorbars"); details.addEventListener("toggle", () => { openErrorBars.set(series.id, details.open); }); + const fillDetails = item.querySelector(".series-fill"); + fillDetails.addEventListener("toggle", () => { + openFill.set(series.id, fillDetails.open); + }); bindSeriesColorControls(item, (color) => updateSeries(series.id, { color })); - item.querySelector(".remove-series").addEventListener("click", () => removeSeries(series.id)); + item.querySelector(".remove-series").addEventListener("click", () => { + const index = getSettings().series.findIndex((x) => x.id === series.id); + const removedFits = removeSeries(series.id); + if (removedFits > 0) addNote(`系列${index + 1}を削除したため、その系列の近似曲線${removedFits}本も削除しました。`); + }); + item.querySelector(".move-series-up").addEventListener("click", () => moveSeries(series.id, -1)); + item.querySelector(".move-series-down").addEventListener("click", () => moveSeries(series.id, 1)); + item.querySelector(".duplicate-series").addEventListener("click", () => duplicateSeries(series.id)); return item; }; @@ -271,7 +350,16 @@ export const syncVisibility = () => { } for (const wrap of document.querySelectorAll("#seriesList .series-source-wrap")) wrap.hidden = !hasManySources(); for (const item of document.querySelectorAll("#seriesList .series-item")) { - syncErrorVisibility(item, settings.series.find((x) => x.id === item.dataset.seriesId), usePerSeriesX); + const s = settings.series.find((x) => x.id === item.dataset.seriesId); + syncErrorVisibility(item, s, usePerSeriesX); + // 棒グラフでは点の形と塗りつぶし帯は使わない(隠す)。点の形が「なし」の折れ線は点サイズを使わない + const isBar = settings.plot.type === "bar"; + const markerWrap = item.querySelector(".series-marker-wrap"); + if (markerWrap) markerWrap.hidden = isBar; + const fill = item.querySelector(".series-fill"); + if (fill) fill.hidden = isBar; + const size = item.querySelector(".series-marker-size"); + if (size && s) size.disabled = !isBar && settings.plot.type === "line" && s.marker === "none"; } const dateGroup = document.getElementById("xDateFormatGroup"); if (dateGroup) dateGroup.hidden = !usesDatetimeX(); @@ -281,6 +369,7 @@ export const syncVisibility = () => { const el = document.getElementById(id); if (el) el.style.display = hasY2 ? "" : "none"; } + for (const hook of visibilityHooks) hook(); }; // 点サイズが自動(null)の系列は、プロット種別に応じた値を表示する(ユーザーが入力した値は変えない) @@ -340,6 +429,13 @@ export const renderSeriesList = () => { removeBtn.setAttribute("aria-label", `系列 ${idx + 1} を削除`); removeBtn.style.opacity = disable ? "0.5" : "1"; removeBtn.style.cursor = disable ? "not-allowed" : "pointer"; + const up = item.querySelector(".move-series-up"); + const down = item.querySelector(".move-series-down"); + up.disabled = idx === 0; + down.disabled = idx === items.length - 1; + up.setAttribute("aria-label", `系列 ${idx + 1} を上へ`); + down.setAttribute("aria-label", `系列 ${idx + 1} を下へ`); + item.querySelector(".duplicate-series").setAttribute("aria-label", `系列 ${idx + 1} を複製`); }); syncVisibility(); }; @@ -398,6 +494,13 @@ export const reconcileColumns = () => { } if (next) patch.errorBars = next; } + // 塗りつぶし帯の列も同じ(もう無い列なら解除し、帯が消えることを知らせる) + if (s.fill && ["lower", "upper"].some((k) => s.fill[k] && !valid.has(s.fill[k]))) { + const fill = { ...s.fill }; + for (const k of ["lower", "upper"]) if (fill[k] && !valid.has(fill[k])) fill[k] = ""; + patch.fill = fill; + addNote(`系列${settings.series.indexOf(s) + 1}: 塗りつぶし帯の列が無くなったため、帯の列を空に戻しました。`); + } if (Object.keys(patch).length) updateSeries(s.id, patch, "reconcile"); } refreshSources(); @@ -411,6 +514,8 @@ const FIELD_BY_CLASS = [ ["series-line-width", "lineWidth", "number"], ["series-line-style", "lineStyle", "text"], ["series-marker-size", "markerSize", "number"], + ["series-marker", "marker", "text"], + ["series-alpha", "alpha", "number"], ["series-legend-name", "label", "text"], ["series-use-y2", "secondaryAxis", "checkbox"], ]; @@ -423,7 +528,12 @@ const onSourceChange = (seriesId, source) => { if (series[0] && series[0].id === seriesId && plot.xColumn) setPath("plot.xColumn", ""); const errorBars = cloneErrorBars(current.errorBars); for (const dir of ["y", "x"]) Object.assign(errorBars[dir], { column: "", columnMinus: "" }); - updateSeries(seriesId, { source, x: "", y: "", errorBars }); + const patch = { source, x: "", y: "", errorBars }; + if (usesFill(current)) { + patch.fill = { ...current.fill, lower: "", upper: "" }; + addNote(`系列${series.indexOf(current) + 1}: データ元を替えたため、塗りつぶし帯の列を空に戻しました(帯は描きません)。`); + } + updateSeries(seriesId, patch); refreshSources(); }; @@ -455,6 +565,11 @@ const onSeriesInput = (event) => { onErrorInput(item.dataset.seriesId, target); return; } + if (target.dataset.fill) { + const current = getSettings().series.find((x) => x.id === item.dataset.seriesId); + if (current) updateSeries(current.id, { fill: { ...current.fill, [target.dataset.fill]: target.dataset.fill === "alpha" ? readNumber(target) : target.value } }); + return; + } const entry = FIELD_BY_CLASS.find(([cls]) => target.classList.contains(cls)); if (!entry) return; const [, field, kind] = entry; diff --git a/tests/e2e/helpers.py b/tests/e2e/helpers.py index fda0a4e..fa8e1cc 100644 --- a/tests/e2e/helpers.py +++ b/tests/e2e/helpers.py @@ -506,3 +506,72 @@ def series_errorbars(page, series_id) -> dict: "(id) => import(new URL('js/state.js', document.baseURI)).then((m) => m.getSettings().series.find((s) => s.id === id).errorBars)", series_id, ) + + +# --- 系列のスタイル・注釈・近似曲線(Phase 5b) --- +def series_ids(page) -> list[str]: + """画面の系列カードの順(id)。""" + return page.eval_on_selector_all("#seriesList .series-item", "els => els.map(e => e.dataset.seriesId)") + + +def series_state(page, series_id) -> dict: + """画面の状態(state)にある系列の設定。""" + return page.evaluate( + "(id) => import(new URL('js/state.js', document.baseURI)).then((m) => m.getSettings().series.find((s) => s.id === id))", + series_id, + ) + + +def state_list(page, key) -> list[dict]: + """state の annotations / fits。""" + return page.evaluate("(k) => import(new URL('js/state.js', document.baseURI)).then((m) => m.getSettings()[k])", key) + + +def set_fill(page, series_id, *, lower=None, upper=None, alpha=None): + """塗りつぶし帯の入力欄を変える(折りたたみが閉じていれば開く。待たない)。""" + page.evaluate("(id) => { document.getElementById(`series-${id}-fill`).open = true; }", series_id) + if lower is not None: + page.select_option(f"#series-{series_id}-fill-lower", lower) + if upper is not None: + page.select_option(f"#series-{series_id}-fill-upper", upper) + if alpha is not None: + page.fill(f"#series-{series_id}-fill-alpha", str(alpha)) + + +def set_card_field(page, selector, value): + """カード内の入力欄を、種類に応じて変える(select は選択、checkbox は切替、それ以外は入力)。待たない。""" + kind = page.evaluate( + "(s) => { const e = document.querySelector(s); return e.type === 'checkbox' ? 'checkbox' : e.tagName.toLowerCase(); }", selector + ) + if kind == "checkbox": + page.set_checked(selector, bool(value)) + elif kind == "select": + page.select_option(selector, value) + else: + page.fill(selector, str(value)) + + +def add_annotation(page, kind="hline", **fields) -> str: + """「+ 注釈を追加」を押し、種類と入力欄(text / coords / x / y / start / end / axis / line-style / line-width / alpha / font-size / label)を設定して id を返す。待たない。""" + before = {a["id"] for a in state_list(page, "annotations")} + page.click("#addAnnotationBtn") + new = [a["id"] for a in state_list(page, "annotations") if a["id"] not in before][0] + page.select_option(f"#annotation-{new}-kind", kind) + for name, value in fields.items(): + set_card_field(page, f"#annotation-{new}-{name.replace('_', '-')}", value) + return new + + +def set_annotation(page, ann_id, **fields): + for name, value in fields.items(): + set_card_field(page, f"#annotation-{ann_id}-{name.replace('_', '-')}", value) + + +def add_fit(page, **fields) -> str: + """「+ 近似曲線を追加」を押し、入力欄(series / model / degree / show / color / line-style)を設定して id を返す。待たない。""" + before = {f["id"] for f in state_list(page, "fits")} + page.click("#addFitBtn") + new = [f["id"] for f in state_list(page, "fits") if f["id"] not in before][0] + for name, value in fields.items(): + set_card_field(page, f"#fit-{new}-{name.replace('_', '-')}", value) + return new diff --git a/tests/e2e/test_annotations.py b/tests/e2e/test_annotations.py new file mode 100644 index 0000000..b357a86 --- /dev/null +++ b/tests/e2e/test_annotations.py @@ -0,0 +1,154 @@ +"""注釈(Phase 5b, G4): 種類ごとの描画、入力欄の出し分け、日時・文字列の X、第2Y軸、凡例、エラーと復帰。""" +import pytest + +from helpers import ( + add_annotation, + code_is_stale, + code_text, + enter_edit_mode, + image_generation, + add_fit, + code_value, + image_summary, + is_hidden_by_id, + load_fixture, + set_annotation, + state_list, + status_kind, + status_text, + wait_app_ready, + wait_code_generated, + wait_error_status, + wait_settled, +) + +pytestmark = pytest.mark.e2e + +X, MEAN, DAY, OTHER = "__idx__0", "__idx__1", "__idx__4", "__idx__5" + + +def start(page, app_url, fixtures_dir, fixture="band.csv", x=X, y=MEAN, plot_type=None): + page.goto(app_url) + wait_app_ready(page) + load_fixture(page, fixtures_dir / fixture) + wait_settled(page) + if plot_type: + page.select_option("#plotType", plot_type) + page.select_option("#series-s1-x", x) + page.select_option("#series-s1-y", y) + wait_settled(page) + + +def counts(page, axis=0): + return image_summary(page)[axis]["annotations"] + + +def test_section_and_every_kind_numeric_x(page, app_url, fixtures_dir, console_log): + start(page, app_url, fixtures_dir) + titles = page.eval_on_selector_all("aside.panel > details.panel-section > summary", "els => els.map(e => e.textContent.trim())") + assert titles.index("注釈・解析") == titles.index("体裁") + 1 == titles.index("保存") - 1 + assert page.is_visible("#addAnnotationBtn") and page.inner_text("#addAnnotationBtn") == "+ 注釈を追加" + h = add_annotation(page, "hline", y="10", label="基準値") + # 種類ごとに出る欄が違う + visible = lambda aid, name: not is_hidden_by_id(page, f"annotation-{aid}-{name}") # noqa: E731 + assert visible(h, "y") and visible(h, "line-style") and visible(h, "label") and visible(h, "alpha") + assert not visible(h, "x") and not visible(h, "text") and not visible(h, "start") and not visible(h, "axis") + assert page.get_attribute(f"#annotation-{h}-y", "placeholder") == "例 1.5" + v = add_annotation(page, "vline", x="5") + sp = add_annotation(page, "vspan", start="2", end="4", label="区間") + hs = add_annotation(page, "hspan", start="5", end="8") + t = add_annotation(page, "text", text="ピーク", x="3", y="8") + assert visible(t, "text") and visible(t, "coords") and visible(t, "font-size") and not visible(t, "line-style") and not visible(t, "label") + wait_settled(page) + wait_code_generated(page) + assert counts(page) == {"texts": 1, "hlines": 1, "vlines": 1, "hspans": 1, "vspans": 1} + legend = image_summary(page)[0]["legend"] + assert "基準値" in legend and "区間" in legend + code = code_value(page) + assert "ax.axhline(" in code and "ax.axvspan(" in code and "ax.text(" in code + # 文字の位置を「図の中の割合」にすると、例が 0〜1 になる + set_annotation(page, t, coords="axes", x="0.05", y="0.95") + wait_settled(page) + assert page.get_attribute(f"#annotation-{t}-x", "placeholder") == "0〜1" and "transAxes" in code_value(page) + # 削除で消える(id は再利用しない) + page.click(f"#annotation-{sp}-remove") + wait_settled(page) + assert counts(page)["vspans"] == 0 and [a["id"] for a in state_list(page, "annotations")] == [h, v, hs, t] + assert add_annotation(page, "hline", y="1") == "a6" + wait_settled(page) + # 入力のエラー: 数として読めない Y。コードタブは「最新でない」、直すと復帰 + set_annotation(page, h, y="abc") + wait_error_status(page) + assert "注釈1" in status_text(page) and code_is_stale(page) + set_annotation(page, h, y="12") + wait_settled(page) + wait_code_generated(page) + assert status_kind(page) != "error" and not code_is_stale(page) + + +def test_datetime_and_category_x_and_secondary_axis(page, app_url, fixtures_dir, console_log): + start(page, app_url, fixtures_dir, x=DAY) + v = add_annotation(page, "vline", x="2026-01-05 12:00") + assert page.get_attribute(f"#annotation-{v}-x", "placeholder") == "例 2026-01-31 12:00" + wait_settled(page) + assert counts(page)["vlines"] == 1 and "pd.Timestamp(" in code_value(page) + set_annotation(page, v, x="5") # 日時の X に数を入れるとエラー + wait_error_status(page) + assert "注釈1" in status_text(page) + # 第2Y軸: 使うときだけ「Y 軸」の欄が出る。右の軸の水平線は ax2 に描く + page.select_option("#series-s1-x", X) + h = add_annotation(page, "hline", y="50") + set_annotation(page, v, x="3") + wait_settled(page) + assert is_hidden_by_id(page, f"annotation-{h}-axis") + page.click("#addSeriesBtn") + page.select_option("#series-s2-x", X) + page.select_option("#series-s2-y", OTHER) + page.check("#series-s2-use-y2") + wait_settled(page) + assert not is_hidden_by_id(page, f"annotation-{h}-axis") and is_hidden_by_id(page, f"annotation-{v}-axis") + set_annotation(page, h, axis="y2") + wait_settled(page) + assert len(image_summary(page)) == 2 + assert counts(page, 1)["hlines"] == 1 and counts(page, 0)["hlines"] == 0 + # 文字列の X: 位置は何番目か(0 始まり) + load_fixture(page, fixtures_dir / "categories.csv") + wait_settled(page) + page.select_option("#series-s1-x", "__idx__0") + page.select_option("#series-s1-y", "__idx__1") + wait_settled(page) + assert page.get_attribute(f"#annotation-{v}-x", "placeholder") == "何番目か(0 始まり)" + set_annotation(page, v, x="1.5") + wait_settled(page) + assert status_kind(page) != "error" and counts(page)["vlines"] == 1 + + +def test_edit_mode_does_not_redraw_for_annotations_or_fits(page, app_url, fixtures_dir, console_log): + start(page, app_url, fixtures_dir) + wait_code_generated(page) + enter_edit_mode(page) + generation, code = image_generation(page), code_text(page) + add_annotation(page, "hline", y="10") + add_fit(page) + page.wait_for_timeout(800) # 再描画の遅延(250 ms)より長く待つ + assert image_generation(page) == generation and code_text(page) == code + assert image_summary(page)[0]["annotations"]["hlines"] == 0 + assert "編集" in status_text(page) + + +def test_narrow_screen_has_no_horizontal_scroll(page, app_url, fixtures_dir, console_log): + page.set_viewport_size({"width": 375, "height": 800}) + start(page, app_url, fixtures_dir) + add_annotation(page, "text", text="ピーク", x="3", y="8") + add_annotation(page, "vspan", start="2", end="4", label="区間") + add_fit(page, model="poly") + page.click("#series-s1-duplicate") + wait_settled(page) + overflow = page.evaluate( + """() => { + const wide = [...document.querySelectorAll('.annotation-item, .fit-item, .series-item')] + .filter((e) => e.scrollWidth > e.clientWidth + 1).map((e) => e.id || e.className); + return {page: document.documentElement.scrollWidth - window.innerWidth, wide}; + }""" + ) + assert overflow["page"] <= 0 and overflow["wide"] == [] diff --git a/tests/e2e/test_codegen_consistency.py b/tests/e2e/test_codegen_consistency.py index 9b5abd0..65c24ca 100644 --- a/tests/e2e/test_codegen_consistency.py +++ b/tests/e2e/test_codegen_consistency.py @@ -13,6 +13,8 @@ from helpers import ( add_files, + add_annotation, + add_fit, add_series_with_source, image_summary, load_fixture, @@ -20,6 +22,7 @@ open_tick_group, paste_text, set_errorbars, + set_fill, wait_data_ready, wait_app_ready, wait_code_contains, @@ -200,6 +203,75 @@ def _configure_errbars_two_files(page): set_errorbars(page, "s2", "y", mode="column", column="__idx__3") +# band.csv の列: 0 x, 1 mean, 2 lo, 3 hi, 4 day, 5 other +def _band_base(page, x="__idx__0"): + page.select_option("#series-s1-x", x) + page.select_option("#series-s1-y", "__idx__1") + + +def _configure_style_line_band(page): + _band_base(page) + page.select_option("#series-s1-marker", "s") + page.fill("#series-s1-alpha", "0.8") + set_fill(page, "s1", lower="__idx__2", upper="__idx__3", alpha=0.3) + + +def _configure_band_datetime_scatter(page): + page.select_option("#plotType", "scatter") + _band_base(page, "__idx__4") + set_fill(page, "s1", lower="__idx__2", upper="__idx__3") + + +def _configure_annotations_numeric(page): + _band_base(page) + add_annotation(page, "hline", y="10", label="基準値", line_width="1.5") + add_annotation(page, "vline", x="5", line_style="solid") + add_annotation(page, "vspan", start="2", end="4", label="区間") + add_annotation(page, "hspan", start="5", end="8", alpha="0.1") + add_annotation(page, "text", text="ピーク $\\alpha$", x="3", y="8", font_size="14") + add_annotation(page, "text", text="左上", coords="axes", x="0.05", y="0.95") + + +def _configure_annotations_datetime(page): + _band_base(page, "__idx__4") + add_annotation(page, "vline", x="2026-01-05 12:00", label="イベント") + add_annotation(page, "vspan", start="2026-01-02", end="2026-01-04") + add_annotation(page, "text", text="注目", x="2026-01-08", y="12") + + +def _configure_annotations_y2(page): + _band_base(page) + page.click("#addSeriesBtn") + page.select_option("#series-s2-x", "__idx__0") + page.select_option("#series-s2-y", "__idx__5") + page.check("#series-s2-use-y2") + add_annotation(page, "hline", y="50", axis="y2", label="右の基準") + add_annotation(page, "hspan", start="60", end="80", axis="y2") + add_annotation(page, "hline", y="10") + + +def _configure_fit_linear_legend(page): + _band_base(page) + page.fill("#series-s1-legend-name", "温度") + add_fit(page) + + +def _configure_fit_poly_text(page): + _band_base(page) + add_fit(page, model="poly", degree="3", show="text", line_style="solid") + add_fit(page, model="linear", show="text") + + +def _configure_fit_y2(page): + _band_base(page) + page.click("#addSeriesBtn") + page.select_option("#series-s2-x", "__idx__0") + page.select_option("#series-s2-y", "__idx__5") + page.check("#series-s2-use-y2") + add_fit(page, series="s2") + add_fit(page, series="s1", show="none") + + # 読込の設定を変えた場合: 生成スクリプトの読込部が、GUI の読み方と同じ図を作る PRE_STEPS = {"preamble_csv": _pre_preamble, "european_csv": _pre_european} @@ -233,6 +305,14 @@ def _paste_fixture(page, fixtures_dir): "errbars_bar": ("categories.csv", _configure_errbars_bar), "errbars_bar_multi": ("categories.csv", _configure_errbars_bar_multi), "errbars_two_files": (("utf8.csv", "errorbars.csv"), _configure_errbars_two_files), + "style_line_band": ("band.csv", _configure_style_line_band), + "band_datetime_scatter": ("band.csv", _configure_band_datetime_scatter), + "annotations_numeric": ("band.csv", _configure_annotations_numeric), + "annotations_datetime": ("band.csv", _configure_annotations_datetime), + "annotations_y2": ("band.csv", _configure_annotations_y2), + "fit_linear_legend": ("band.csv", _configure_fit_linear_legend), + "fit_poly_text": ("band.csv", _configure_fit_poly_text), + "fit_y2": ("band.csv", _configure_fit_y2), "scatter_paper1": ("utf8.csv", _configure_scatter_paper1), "scatter_arimo_paper2_pdf": ("utf8.csv", _configure_scatter_arimo_paper2_pdf), } @@ -256,7 +336,10 @@ def l_ax_summary(summary, key): return summary[0][key] -EXACT_KEYS = ("title", "xlabel", "ylabel", "xscale", "yscale", "lines", "collections", "patches", "legend") +EXACT_KEYS = ( + "title", "xlabel", "ylabel", "xscale", "yscale", "lines", "collections", "patches", "legend", + "bands", "markers", "alphas", "annotations", "fitlines", "fittexts", # Phase 5b +) @pytest.mark.parametrize("case", list(CASES)) @@ -299,7 +382,7 @@ def test_downloaded_script_matches_browser_figure(case, page, app_url, fixtures_ local, stderr = _run_in_cpython(script, tmp_path) assert len(local) == len(browser) - assert len(browser) == (2 if case == "line" else 1) + assert len(browser) == (2 if case in ("line", "annotations_y2", "fit_y2") else 1) if case.startswith("errbars_"): assert browser[0]["errorbars"] > 0 assert l_ax_summary(local, "errorbars") == l_ax_summary(browser, "errorbars") @@ -362,6 +445,26 @@ def test_downloaded_script_matches_browser_figure(case, page, app_url, fixtures_ assert "df2.iloc[:, 3]" in script.read_text(encoding="utf-8") if case in ("errbars_bar", "errbars_bar_multi"): assert local[0]["xticklabels"] == browser[0]["xticklabels"] + if case == "style_line_band": + assert browser[0]["bands"] == 1 and browser[0]["markers"] == ["s"] and browser[0]["alphas"] == [0.8] + if case == "band_datetime_scatter": + assert browser[0]["bands"] == 1 and local[0]["xticklabels"] == browser[0]["xticklabels"] + if case == "annotations_numeric": + assert browser[0]["annotations"] == {"texts": 2, "hlines": 1, "vlines": 1, "hspans": 1, "vspans": 1} + assert "基準値" in browser[0]["legend"] and "区間" in browser[0]["legend"] + if case == "annotations_datetime": + assert browser[0]["annotations"] == {"texts": 1, "hlines": 0, "vlines": 1, "hspans": 0, "vspans": 1} + assert "pd.Timestamp(" in script.read_text(encoding="utf-8") + if case == "annotations_y2": + assert browser[1]["annotations"]["hlines"] == 1 and browser[1]["annotations"]["hspans"] == 1 + assert browser[0]["annotations"]["hlines"] == 1 + if case == "fit_linear_legend": + assert browser[0]["fitlines"] == 1 and any(t.startswith("温度の近似") for t in browser[0]["legend"]) + assert "poly_text(" in script.read_text(encoding="utf-8") + if case == "fit_poly_text": + assert browser[0]["fitlines"] == 2 and browser[0]["fittexts"] == 2 + if case == "fit_y2": + assert browser[1]["fitlines"] == 1 and browser[0]["fitlines"] == 1 if case == "line": assert browser[0]["yscale"] == "log" and browser[0]["lines"] == 1 and browser[1]["lines"] == 1 assert browser[0]["legend"] == ["指数 [1]", "線形 [2]"] diff --git a/tests/e2e/test_fits.py b/tests/e2e/test_fits.py new file mode 100644 index 0000000..5894413 --- /dev/null +++ b/tests/e2e/test_fits.py @@ -0,0 +1,98 @@ +"""近似曲線(Phase 5b, G5): 凡例・図の中の式、棒グラフで隠れる、日時の X のエラー、系列の削除。""" +import pytest + +from helpers import ( + add_fit, + code_value, + image_summary, + is_hidden_by_id, + load_fixture, + state_list, + status_text, + status_warnings, + wait_app_ready, + wait_error_status, + wait_settled, +) + +pytestmark = pytest.mark.e2e + +X, MEAN, DAY, OTHER = "__idx__0", "__idx__1", "__idx__4", "__idx__5" + + +def start(page, app_url, fixtures_dir): + page.goto(app_url) + wait_app_ready(page) + load_fixture(page, fixtures_dir / "band.csv") + wait_settled(page) + page.select_option("#series-s1-x", X) + page.select_option("#series-s1-y", MEAN) + page.fill("#series-s1-legend-name", "温度") + wait_settled(page) + + +def test_linear_legend_poly_text_and_series_select(page, app_url, fixtures_dir, console_log): + start(page, app_url, fixtures_dir) + assert "対数軸" in page.inner_text("#sectionAnalysis") # 近似は元の値で行う、という補足 + f = add_fit(page) + assert page.eval_on_selector(f"#fit-{f}-series", "e => e.selectedOptions[0].textContent") == "系列1(温度)" + assert is_hidden_by_id(page, f"fit-{f}-degree") + wait_settled(page) + s = image_summary(page)[0] + assert s["fitlines"] == 1 and s["fittexts"] == 0 + label = [t for t in s["legend"] if t.startswith("温度の近似")] + assert label and "y = " in label[0] and "R" in label[0] + # 多項式で図の中に出す: 次数の欄が出る。式は凡例ではなく図の中 + page.select_option(f"#fit-{f}-model", "poly") + assert not is_hidden_by_id(page, f"fit-{f}-degree") + page.fill(f"#fit-{f}-degree", "3") + page.select_option(f"#fit-{f}-show", "text") + wait_settled(page) + s = image_summary(page)[0] + assert s["fitlines"] == 1 and s["fittexts"] == 1 and not [t for t in s["legend"] if "近似" in t] + assert "poly_text(" in code_value(page) + # 線の色: 「系列の色」のときは色の選択が隠れ、「色を選ぶ」で出る + assert is_hidden_by_id(page, f"fit-{f}-color-picker-trigger") + page.select_option(f"#fit-{f}-color", "custom") + assert not is_hidden_by_id(page, f"fit-{f}-color-picker-trigger") + assert state_list(page, "fits")[0]["color"] != "" + # 系列の名前を変えると選択肢に追従する。系列を足すと選べる + page.fill("#series-s1-legend-name", "気温") + page.click("#addSeriesBtn") + page.select_option("#series-s2-x", X) + page.select_option("#series-s2-y", OTHER) + wait_settled(page) + texts = page.eval_on_selector(f"#fit-{f}-series", "e => [...e.options].map(o => o.textContent)") + assert texts[0] == "系列1(気温)" and texts[1].startswith("系列2") + page.select_option(f"#fit-{f}-series", "s2") + wait_settled(page) + assert state_list(page, "fits")[0]["series"] == "s2" + # 棒グラフでは一覧と追加ボタンを隠し、案内を出す。値は残る + page.select_option("#plotType", "bar") + page.select_option("#xColumn", X) + wait_settled(page) + assert is_hidden_by_id(page, "fitList") and is_hidden_by_id(page, "addFitBtn") + assert page.inner_text("#fitBarNote") == "棒グラフでは近似曲線は使えません。" + assert image_summary(page)[0]["fitlines"] == 0 + page.select_option("#plotType", "line") + wait_settled(page) + assert not is_hidden_by_id(page, "fitList") and is_hidden_by_id(page, "fitBarNote") + # 系列を削除すると、その近似曲線も消え、知らせる + page.click("#series-s2-remove") + wait_settled(page) + assert state_list(page, "fits") == [] and page.locator("#fitList .fit-item").count() == 0 + assert any("近似曲線" in w for w in status_warnings(page)) + assert image_summary(page)[0]["fitlines"] == 0 + + +def test_datetime_x_is_an_error_and_recovers(page, app_url, fixtures_dir, console_log): + start(page, app_url, fixtures_dir) + add_fit(page) + wait_settled(page) + assert image_summary(page)[0]["fitlines"] == 1 + page.select_option("#series-s1-x", DAY) + wait_error_status(page) + assert "近似曲線" in status_text(page) + page.select_option("#series-s1-x", X) + wait_settled(page) + assert image_summary(page)[0]["fitlines"] == 1 diff --git a/tests/e2e/test_panel_sections.py b/tests/e2e/test_panel_sections.py index 9e35484..311c01d 100644 --- a/tests/e2e/test_panel_sections.py +++ b/tests/e2e/test_panel_sections.py @@ -9,6 +9,7 @@ ("sectionSeries", "系列"), ("sectionAxes", "軸・目盛"), ("sectionStyle", "体裁"), + ("sectionAnalysis", "注釈・解析"), ("sectionSave", "保存"), ] diff --git a/tests/e2e/test_series_style.py b/tests/e2e/test_series_style.py new file mode 100644 index 0000000..c4a824f --- /dev/null +++ b/tests/e2e/test_series_style.py @@ -0,0 +1,141 @@ +"""系列のスタイル(Phase 5b, G3): 点の形・不透明度・塗りつぶし帯・並べ替え・複製。""" +import pytest + +from helpers import ( + add_files, + code_value, + image_summary, + is_hidden_by_id, + load_fixture, + series_ids, + series_state, + set_fill, + state_list, + status_kind, + status_text, + status_warnings, + wait_app_ready, + wait_code_generated, + wait_error_status, + wait_settled, +) + +pytestmark = pytest.mark.e2e + +# band.csv の列: 0 x, 1 mean, 2 lo, 3 hi, 4 day, 5 other +X, MEAN, LO, HI, DAY, OTHER = (f"__idx__{i}" for i in range(6)) + + +def start(page, app_url, fixtures_dir, fixture="band.csv", plot_type=None): + page.goto(app_url) + wait_app_ready(page) + load_fixture(page, fixtures_dir / fixture) + wait_settled(page) + if plot_type: + page.select_option("#plotType", plot_type) + page.select_option("#series-s1-x", X) + page.select_option("#series-s1-y", MEAN) + wait_settled(page) + + +def test_marker_alpha_and_band(page, app_url, fixtures_dir, console_log): + start(page, app_url, fixtures_dir) + assert image_summary(page)[0]["bands"] == 0 and image_summary(page)[0]["markers"] == ["None"] + assert page.evaluate("document.getElementById('series-s1-fill').open") is False # 既定は閉じている + assert page.inner_text("#series-s1-fill > summary") == "塗りつぶし帯" + assert page.eval_on_selector("#series-s1-alpha", "e => e.labels[0].textContent") == "不透明度" + # 点の形: 形を選ぶと点が描かれ、「なし」では点サイズの欄が使えない + page.select_option("#series-s1-marker", "s") + wait_settled(page) + assert image_summary(page)[0]["markers"] == ["s"] + assert "marker=" in code_value(page) + assert not page.is_disabled("#series-s1-marker-size") + page.select_option("#series-s1-marker", "none") + wait_settled(page) + assert page.is_disabled("#series-s1-marker-size") and image_summary(page)[0]["markers"] == ["None"] + page.select_option("#series-s1-marker", "auto") + # 不透明度 + page.fill("#series-s1-alpha", "0.5") + wait_settled(page) + assert image_summary(page)[0]["alphas"] == [0.5] and "alpha=0.5" in code_value(page) + # 塗りつぶし帯: 下端だけではエラー、両方で帯。数値にできない値は警告 + set_fill(page, "s1", lower=LO) + wait_error_status(page) + assert "塗りつぶし帯" in status_text(page) + set_fill(page, "s1", upper=HI) + wait_settled(page) + wait_code_generated(page) + assert status_kind(page) == "warning" and any("下端" in w or "塗りつぶし" in w for w in status_warnings(page)) + assert image_summary(page)[0]["bands"] == 1 and "fill_between(" in code_value(page) + assert page.evaluate("document.getElementById('series-s1-fill').open") is True + # 棒グラフでは点の形と帯を隠す(不透明度は残る)。値は残り、帯は描かれない + page.select_option("#plotType", "bar") + page.select_option("#xColumn", X) + wait_settled(page) + assert is_hidden_by_id(page, "series-s1-marker") and is_hidden_by_id(page, "series-s1-fill-lower") + assert not is_hidden_by_id(page, "series-s1-alpha") + assert image_summary(page)[0]["bands"] == 0 + page.select_option("#plotType", "line") + wait_settled(page) + assert image_summary(page)[0]["bands"] == 1 + # scatter で「なし」は点が見えないのでエラー + page.select_option("#plotType", "scatter") + page.select_option("#series-s1-marker", "none") + wait_error_status(page) + assert "点の形" in status_text(page) + page.select_option("#series-s1-marker", "auto") + wait_settled(page) + assert status_kind(page) != "error" + + +def test_band_with_datetime_x(page, app_url, fixtures_dir, console_log): + start(page, app_url, fixtures_dir, plot_type="scatter") + page.select_option("#series-s1-x", DAY) + set_fill(page, "s1", lower=LO, upper=HI, alpha=0.4) + wait_settled(page) + assert image_summary(page)[0]["bands"] == 1 and "alpha=0.4" in code_value(page) + + +def test_source_change_clears_band(page, app_url, fixtures_dir, console_log): + start(page, app_url, fixtures_dir) + set_fill(page, "s1", lower=LO, upper=HI) + wait_settled(page) + assert image_summary(page)[0]["bands"] == 1 + add_files(page, [fixtures_dir / "errorbars.csv"]) + page.select_option("#series-s1-source", "d2") + wait_settled(page) + state = series_state(page, "s1") + assert state["fill"]["lower"] == "" and state["fill"]["upper"] == "" + assert page.input_value("#series-s1-fill-lower") == "" + assert any("塗りつぶし帯" in w for w in status_warnings(page)) + + +def test_reorder_and_duplicate(page, app_url, fixtures_dir, console_log): + start(page, app_url, fixtures_dir) + page.fill("#series-s1-legend-name", "平均") + page.click("#addSeriesBtn") + page.select_option("#series-s2-x", X) + page.select_option("#series-s2-y", OTHER) + page.fill("#series-s2-legend-name", "別") + wait_settled(page) + assert series_ids(page) == ["s1", "s2"] and image_summary(page)[0]["legend"] == ["平均", "別"] + # 端のボタンは無効、aria-label がある + assert page.is_disabled("#series-s1-up") and page.is_disabled("#series-s2-down") + assert page.get_attribute("#series-s1-down", "aria-label") == "系列 1 を下へ" + assert page.get_attribute("#series-s2-duplicate", "aria-label") == "系列 2 を複製" + page.click("#series-s1-down") + wait_settled(page) + assert series_ids(page) == ["s2", "s1"] and image_summary(page)[0]["legend"] == ["別", "平均"] + assert page.is_disabled("#series-s2-up") and not page.is_disabled("#series-s2-down") + # 複製: 元の系列の直後。色は別、設定は同じ、id は新しい + page.fill("#series-s1-alpha", "0.6") + page.select_option("#series-s1-marker", "^") + wait_settled(page) + page.click("#series-s1-duplicate") + wait_settled(page) + ids = series_ids(page) + assert ids[:2] == ["s2", "s1"] and ids[2] not in ("s1", "s2") and len(ids) == 3 and ids[2] == "s3" + copy, src = series_state(page, "s3"), series_state(page, "s1") + assert copy["color"] != src["color"] and copy["marker"] == "^" and copy["alpha"] == 0.6 and copy["y"] == src["y"] + assert image_summary(page)[0]["legend"] == ["別", "平均", "平均"] + assert state_list(page, "fits") == [] diff --git a/tests/fixtures/README.md b/tests/fixtures/README.md index f3d31fc..699a665 100644 --- a/tests/fixtures/README.md +++ b/tests/fixtures/README.md @@ -24,3 +24,4 @@ | `dates_ja.csv` | `2026年1月5日` 形式の日付(時刻なし、8行)と売上。棒グラフ用 | | `datetime.xlsx` | Excel の日時セル(datetime 型、6時間刻みで24行)/ 値 / 温度 | | `errorbars.csv` | エラーバー用。x(0〜11)/ y / y2 / sd(4行目は空欄、7行目は `bad`、10行目は負の値 `-0.2`)/ sd_low / sd_high(上下で別の誤差)/ xsd(X 方向の誤差) | +| `band.csv` | 塗りつぶし帯・近似曲線・注釈用(5b)。x(0〜11)/ mean(ほぼ直線)/ lo・hi(帯の下端・上端。lo の7行目は `bad`)/ day(`2026-01-01` からの日付)/ other(別の系列用。右下がり) | diff --git a/tests/fixtures/band.csv b/tests/fixtures/band.csv new file mode 100644 index 0000000..b5f8e3d --- /dev/null +++ b/tests/fixtures/band.csv @@ -0,0 +1,13 @@ +x,mean,lo,hi,day,other +0,2.0,1.0,3.2,2026-01-01,100 +1,3.837,2.837,5.037,2026-01-02,97 +2,5.364,4.364,6.564,2026-01-03,94 +3,6.556,5.556,7.756,2026-01-04,91 +4,7.697,6.697,8.897,2026-01-05,88 +5,9.116,8.116,10.316,2026-01-06,85 +6,10.888,bad,12.088,2026-01-07,82 +7,12.763,11.763,13.963,2026-01-08,79 +8,14.396,13.396,15.596,2026-01-09,76 +9,15.665,14.665,16.865,2026-01-10,73 +10,16.782,15.782,17.982,2026-01-11,70 +11,18.1,17.1,19.3,2026-01-12,67 diff --git a/tests/fixtures/make_fixtures.py b/tests/fixtures/make_fixtures.py index 2bfd03c..12aa474 100644 --- a/tests/fixtures/make_fixtures.py +++ b/tests/fixtures/make_fixtures.py @@ -147,6 +147,7 @@ def main(): make_datetime_fixtures(fixed) make_errorbar_fixture() + make_band_fixture() def make_errorbar_fixture(): @@ -167,6 +168,17 @@ def make_errorbar_fixture(): (OUT / "errorbars.csv").write_bytes(("\n".join(lines) + "\n").encode("utf-8")) +def make_band_fixture(): + """塗りつぶし帯・近似曲線・注釈(5b)。x / mean(ほぼ直線)/ lo / hi(帯の下端・上端。7行目の lo は `bad`)/ day(日付)/ other(別の系列用)。""" + lines = ["x,mean,lo,hi,day,other"] + for i in range(12): + mean = round(2.0 + 1.5 * i + 0.4 * math.sin(i), 3) + lo = "bad" if i == 6 else str(round(mean - 1.0, 3)) + day = (datetime(2026, 1, 1) + timedelta(days=i)).strftime("%Y-%m-%d") + lines.append(f"{i},{mean},{lo},{round(mean + 1.2, 3)},{day},{round(100 - 3 * i, 2)}") + (OUT / "band.csv").write_bytes(("\n".join(lines) + "\n").encode("utf-8")) + + def make_datetime_fixtures(fixed): """日時の列(D5)。年をまたぐ時間刻み、ISO 8601(タイムゾーン付き)、日本語の日付、Excel の日時セル。""" # 時間刻み。値は 150 行(先頭 100 行は正しい日時。120 行目は読めない値、130 行目は空欄) diff --git a/tests/unit/test_js_modules.py b/tests/unit/test_js_modules.py index e96682d..503915f 100644 --- a/tests/unit/test_js_modules.py +++ b/tests/unit/test_js_modules.py @@ -163,3 +163,70 @@ def test_add_series_without_preset_is_unchanged(tmp_path): files = {"state.js": "js/state.js", "defaults.js": "js/defaults.js", "palettes.js": "js/palettes.js", "presets.js": "js/presets.js"} res = run_node(tmp_path, files, script) assert res["lineWidth"] == 2 and res["markerSize"] is None and res["color"] == "#005AFF" + + +STATE_FILES = {"state.js": "js/state.js", "defaults.js": "js/defaults.js", "palettes.js": "js/palettes.js", "presets.js": "js/presets.js"} + + +@needs_node +def test_move_and_duplicate_series(tmp_path): + script = """ + import { addSeries, addFit, duplicateSeries, getSettings, moveSeries, updateSeries } from "./state.js"; + const a = addSeries(); const b = addSeries(); + const ids = () => getSettings().series.map((s) => s.id); + const out = { start: ids() }; + moveSeries("s1", -1); out.top_stays = ids(); + moveSeries("s1", 1); out.moved = ids(); + moveSeries(b.id, 1); out.bottom_stays = ids(); + updateSeries("s1", { marker: "s", alpha: 0.5, fill: { lower: "__idx__2", upper: "__idx__3", alpha: 0.4 } }); + addFit(); + const copy = duplicateSeries("s1"); + out.after = ids(); + out.copy = copy; + out.src_color = getSettings().series.find((s) => s.id === "s1").color; + out.fits = getSettings().fits.length; + copy.fill.lower = ""; // 複製は深いコピー + out.src_fill = getSettings().series.find((s) => s.id === "s1").fill.lower; + console.log(JSON.stringify(out)); + """ + res = run_node(tmp_path, STATE_FILES, script) + assert res["start"] == ["s1", "s2", "s3"] + assert res["top_stays"] == ["s1", "s2", "s3"] + assert res["moved"] == ["s2", "s1", "s3"] + assert res["bottom_stays"] == res["moved"] + assert res["after"] == ["s2", "s1", "s4", "s3"] # 元の系列の直後 + copy = res["copy"] + assert copy["id"] == "s4" and copy["marker"] == "s" and copy["alpha"] == 0.5 + assert copy["fill"]["upper"] == "__idx__3" and copy["color"] != res["src_color"] + assert res["fits"] == 1 and res["src_fill"] == "__idx__2" + + +@needs_node +def test_annotations_fits_and_removing_series(tmp_path): + script = """ + import { addAnnotation, addFit, addSeries, getSettings, removeAnnotation, removeFit, removeSeries, subscribe, updateAnnotation, updateFit } from "./state.js"; + const kinds = []; subscribe((_s, c) => kinds.push(c.kind)); + const out = {}; + const a1 = addAnnotation(); const a2 = addAnnotation(); + out.ann_ids = [a1.id, a2.id]; + updateAnnotation("a1", { kind: "text", text: "ピーク" }); + removeAnnotation("a1"); + out.ann_after = getSettings().annotations.map((a) => [a.id, a.kind]); + out.ann_next = addAnnotation().id; + addSeries(); + const f1 = addFit(); updateFit("f1", { series: "s2", model: "poly" }); const f2 = addFit(); + out.fit_ids = [f1.id, f2.id]; out.f1 = getSettings().fits[0]; + removeFit("f2"); out.fit_next = addFit().id; // f3(f2 は再利用しない) + out.removed = removeSeries("s2"); + out.fits_left = getSettings().fits.map((f) => [f.id, f.series]); + out.last = removeSeries("s1"); + out.kinds = [...new Set(kinds)]; + console.log(JSON.stringify(out)); + """ + res = run_node(tmp_path, STATE_FILES, script) + assert res["ann_ids"] == ["a1", "a2"] and res["ann_after"] == [["a2", "hline"]] and res["ann_next"] == "a3" + assert res["fit_ids"] == ["f1", "f2"] and res["fit_next"] == "f3" + assert res["f1"]["series"] == "s2" and res["f1"]["model"] == "poly" and res["f1"]["degree"] == 2 + assert res["removed"] == 1 and res["fits_left"] == [["f3", "s1"]] + assert res["last"] == -1 # 系列が1つだけなら消さない + assert {"annotation-list", "annotation-field", "fit-list", "fit-field", "series-list"} <= set(res["kinds"]) From 3361e54de1a58fb5b2da89c13ca032c97ec550b2 Mon Sep 17 00:00:00 2001 From: mioupa <79833278+mioupa@users.noreply.github.com> Date: Tue, 10 Nov 2026 18:32:06 +0900 Subject: [PATCH 4/6] =?UTF-8?q?Name=20annotation=20position=20errors=20lik?= =?UTF-8?q?e=20the=20other=20fields=20(=E6=B3=A8=E9=87=88N=E3=81=AEX)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- py/mplgui/settings.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/py/mplgui/settings.py b/py/mplgui/settings.py index 1e37686..11c6a3a 100644 --- a/py/mplgui/settings.py +++ b/py/mplgui/settings.py @@ -859,15 +859,15 @@ def f(label: str) -> str: values.update( text=text, coords=coords, - x=_position_text(a["x"], "X", f"{owner} X"), - y=_position_text(a["y"], "Y", f"{owner} Y"), + x=_position_text(a["x"], "X", f("X")), + y=_position_text(a["y"], "Y", f("Y")), font_size=_number(a["fontSize"], "文字の大きさ", default=None, exclusive_min=0, owner=owner, field_name=f("文字の大きさ")), ) else: if kind == "vline": - values["x"] = _position_text(a["x"], "X", f"{owner} X") + values["x"] = _position_text(a["x"], "X", f("X")) elif kind == "hline": - values["y"] = _position_text(a["y"], "Y", f"{owner} Y") + values["y"] = _position_text(a["y"], "Y", f("Y")) else: values["start"] = _position_text(a["start"], "開始", f("開始")) values["end"] = _position_text(a["end"], "終了", f("終了")) From 8a4fe8220efdfb76e90617181bcd402010aaf398 Mon Sep 17 00:00:00 2001 From: mioupa <79833278+mioupa@users.noreply.github.com> Date: Tue, 10 Nov 2026 18:32:06 +0900 Subject: [PATCH 5/6] Measure Phase 5b performance: bands, fits and annotations Co-Authored-By: Claude Opus 5.5 --- docs/PERFORMANCE.md | 71 +++++++++++++++++++++++++++++++++++++++++++++ tests/perf/bench.py | 53 +++++++++++++++++++++++++++++++-- 2 files changed, 122 insertions(+), 2 deletions(-) diff --git a/docs/PERFORMANCE.md b/docs/PERFORMANCE.md index 3b88278..1730bb8 100644 --- a/docs/PERFORMANCE.md +++ b/docs/PERFORMANCE.md @@ -375,3 +375,74 @@ Phase 3 後より 5% を超えて悪くなった既存項目は無い(日本 - コールド・ウォーム起動、日本語フォント取得は +4% 前後で、マシンの状態のぶれの範囲とみられる。 - これらを調べるため、CPython で Phase 4 のコード(21c91df)と現在のコードを比べた。描画(193 ms と 188 ms)と保存(557 ms と 570 ms)は差がなく(ぶれの範囲)、差が出たのは日時の読込だけで、ネイティブで +3.5 ms だった。日時の列に対して `numericLike` を作るときの、10,000 個の Timestamp を1つずつ調べるループが原因で、`looks_numeric` が日時の列をすぐ False にするよう直した(`dataprep` は日時の X には呼ばないので、結果は変わらない)。この PR が変えていない起動も、同じ計測の中で +4% 前後遅かった。読込・貼り付け・保存・コピーに残る +5〜17% は、マシンの状態の回ごとのぶれとみている(表の既存の行は、1回通しで計測したままにしている)。 - 確かめるため、読込の項目(`--only new`。Phase 4 で足した項目)だけを、Phase 4 のコード(21c91df)と現在のコード(`numericLike` の修正後)で続けて計測した(各 N=5)。差はすべて +4% 未満で、Phase 4 後と同等だった: 貼り付け 10,000 行 182 → 184 ms(+1%)、貼り付け 30 行 131 → 136 ms(+4%)、xlsx 初回 847 → 857 ms(+1%)、シート切り替え 473 → 477 ms(+1%)、日時の読込 239 → 241 ms(+1%)、2ファイルの読込 210 → 213 ms(+1%)、2ファイルの設定変更 346 → 348 ms(+1%)。1回通しの計測で出た +8〜17% は、その回のマシンの状態によるもの。保存(+6%)とコピー(+7%)は続けての計測をしていないが、CPython の比較で保存の経路に差が無く、同じ回の起動も +4〜5% 遅かったので、同じくぶれとみている。 + + +## Phase 5b 後 + +### 計測条件 + +| 項目 | 内容 | +|---|---| +| 日付 | 2026-11-10 | +| 対象 | `cf78b4c`(Phase 5b: 点の形・不透明度・塗りつぶし帯、注釈、近似曲線、「注釈・解析」の区分)に、Phase 5b の計測行を追加した `tests/perf/bench.py` を組み合わせたもの。PyScript 2026.7.3 / Pyodide 314.0.3 | +| マシン | Mac16,10 / Apple M4 / メモリ 24 GB | +| OS | macOS 27.0.1 | +| ブラウザ | Chromium 153.0.8010.12(Playwright、ヘッドレス) | +| ネットワーク | 実ネットワーク(Phase 5a 後と同じ) | +| 配信 | ローカルの静的 HTTP サーバー(127.0.0.1、サブパスなし) | +| 反復 | 各項目 N=5、全項目を1回通しで計測(再計測なし)。既存項目の計測方法は Phase 5a 後と同じ | + +追加した項目(`--only p5b`。既存項目の方法は変えていない。データは実行時に生成し、コミットしない): + +- 「帯・近似曲線・注釈」: 10,000 行 × 16 列(X + Y 5列 + 帯の下端 5列 + 帯の上端 5列)の CSV。系列5本(Y = 列1〜5)のすべてに、塗りつぶし帯(下端 = 列6〜10、上端 = 列11〜15)と1次の近似曲線(式と R² を凡例に表示)を付け、注釈を3つ(水平線・縦の帯・文字)置く。`data-summary` に帯 5・近似線 5・水平線・縦の帯・文字が出て描画が収束するのを待ってから、既存の「設定変更」と同じ方法(タイトルの `input` → 新しい画像。デバウンス 250 ms 込みと除いた値)で測る。 + +### 結果(ミリ秒、中央値 / 最小 / 最大) + +| 項目 | Phase 5a 後 | Phase 5b 後 | Phase 5a 後比 | +|---|---:|---:|---| +| コールド起動 | 3,769 | 3,697 / 3,688 / 6,703 | 同等(-2%) | +| ウォーム起動 | 3,566 | 3,568 / 3,557 / 3,577 | 同等(+0%) | +| 初回ファイル読込 → 最初のプロット | 187 | 186 / 185 / 189 | 同等(-1%) | +| 設定変更 → プロット更新(デバウンス込み) | 471 | 476 / 464 / 481 | 同等(+1%) | +| 同上(デバウンス 250ms 除く) | 221 | 226 / 214 / 231 | 同等(+2%) | +| 保存(PNG、クリック → ダウンロード開始。既定の 300 dpi) | 407 | 417 / 401 / 426 | 同等(+2%) | +| 初回 .xlsx 読込 → 最初のプロット | 336 | 341 / 339 / 342 | 同等(+1%) | +| 編集モードでの実行(Ctrl/Cmd+Enter → プロット更新) | 594 | 598 / 593 / 601 | 同等(+1%) | +| 保存(PNG、120 dpi) | 266 | 243 / 237 / 272 | 同等(-9%) | +| 保存(PNG、300 dpi。別測定) | 409 | 411 / 400 / 424 | 同等(+1%) | +| 欧文フォント選択 → プロット更新、初回(Arimo を jsDelivr から取得) | 463 | 475 / 470 / 477 | 同等(+3%) | +| 同上、Cache Storage にあるとき | 471 | 474 / 469 / 485 | 同等(+1%) | +| 参考: 欧文フォント初回の、選択 → `data-latin-font-state=ready` | 29 | 35 / 32 / 39 | 参考値(+20%。数 ms の差。A/B では同等) | +| クリップボードへのコピー(クリック → done、300 dpi) | 433 | 418 / 411 / 419 | 同等(-4%) | +| 日本語フォント取得、コールド(ナビゲーション開始 → `font-state=ready`) | 3,840 | 3,806 / 3,788 / 3,860 | 同等(-1%) | +| 同上、Python 準備完了からの追加待ち | 60 | 75 / 57 / 113 | 参考値(+24%。十数 ms の差。A/B では同等) | +| 貼り付け(10,000 行 × 6 列)→ 最初のプロット | 194 | 190 / 189 / 191 | 同等(-2%) | +| 貼り付け(30 行 × 3 列)→ 最初のプロット | 145 | 139 / 137 / 139 | 同等(-4%) | +| xlsx(2 シート × 10,000 行)初回読込 → 最初のプロット | 871 | 872 / 866 / 873 | 同等(+0%) | +| xlsx のシート切り替え → プロット更新(系列5本) | 481 | 490 / 486 / 490 | 同等(+2%) | +| 日時の列を含む 10,000 行の読込 → 最初のプロット | 278 | 247 / 246 / 249 | 同等(-11%) | +| 同、X = 日時で設定変更 → プロット更新(デバウンス込み、系列5本) | 484 | 491 / 488 / 493 | 同等(+1%) | +| 同上(デバウンス 250ms 除く) | 234 | 241 / 238 / 243 | 同等(+3%) | +| 2ファイル(各 10,000 行)の読込 → 最初のプロット | 232 | 219 / 217 / 222 | 同等(-6%) | +| 2ファイルで設定変更 → プロット更新(デバウンス込み、系列2本) | 340 | 350 / 349 / 352 | 同等(+3%) | +| 同上(デバウンス 250ms 除く) | 90 | 100 / 99 / 102 | +11%(下記。A/B では同等) | +| エラーバー(系列5本すべて)の設定変更 → プロット更新 | 795 | 803 / 795 / 817 | 同等(+1%) | +| 同(デバウンス除く) | 545 | 553 / 545 / 567 | 同等(+1%) | +| 目盛・枠線を設定した設定変更 → プロット更新 | 502 | 508 / 505 / 510 | 同等(+1%) | +| 同(デバウンス除く) | 252 | 258 / 255 / 260 | 同等(+2%) | +| 帯・近似曲線・注釈(系列5本すべてに帯と近似曲線、注釈3つ)の設定変更 → プロット更新 | (項目なし) | 718 / 703 / 724 | 新項目(帯・近似・注釈なしの 476 ms に対して +242 ms) | +| 同(デバウンス除く) | (項目なし) | 468 / 453 / 474 | 新項目(帯・近似・注釈なしの 226 ms に対して +242 ms) | + +### 要件の確認 + +要件「設定変更後 1 秒以内の再描画(10,000 行 × 5 系列)」: 既存の設定変更は、デバウンス 250 ms を含めて中央値 476 ms で、**満たしている**。5 系列すべてに塗りつぶし帯と1次の近似曲線を付け、注釈を3つ置いた場合は中央値 718 ms(最大 724 ms)で、**満たしている**(余裕は約 280 ms。デバウンスを除いた描画は 468 ms)。エラーバー(803 ms)、目盛・枠線(508 ms)も引き続き満たしている。 + +### 分析 + +- **帯・近似曲線・注釈**: 描画(デバウンス除く)は、設定なしの 226 ms から 468 ms になり、約 +242 ms。設計時の見込み(帯だけで +100 ms 前後)より大きいが、帯 5 本(10,000 点)に加えて近似曲線 5 本(200 点)と注釈の線・帯・文字が入っていること、凡例の位置「best」(アプリの既定)の探索が図の頂点や artist を増えた分だけ調べることによる増分と考えられる。1 秒に対して余裕があるので、この PR では対策していない。系列数や点数が増える場合は再計測する。 +- **既存項目**: 5% を超えて悪くなった行は3つだけで、いずれも差が小さい。 + - 2ファイルの設定変更(デバウンス除く): 90 → 100 ms(+11%、差 10 ms)。 + - 参考値の欧文フォント初回の `latin-font-state=ready` までの時間: 29 → 35 ms(+20%、差 6 ms)。 + - 参考値の日本語フォントの、Python 準備完了からの追加待ち: 60 → 75 ms(+24%、差 15 ms。最大 113 ms とばらつきも大きい)。 + - 該当する項目の群(`--only new` と `--only old`)だけを、Phase 5a のコード(`b6af00c`)と現在のコードで続けて計測した(各 N=5。5a のコードは一時的な git worktree から配信し、計測後に削除した)。結果は同等だった: 2ファイルの設定変更(デバウンス除く)97 → 98 ms(+1%)、同(デバウンス込み)347 → 348 ms(+0%)、欧文フォント初回の ready までの時間 37 → 37 ms、日本語フォントの追加待ち 77 → 60 ms(5a 側に 179 ms の外れ値)。1回通しの計測で出た差は、その回のマシンの状態によるぶれ(数 ms〜十数 ms)で、5b のコードによる劣化ではない。 + - 残りの既存項目は、描画・読込・保存・コピー・起動のいずれも ±5% 以内(改善した行もあるが、これも回ごとのぶれの範囲)。Phase 5b は既定の設定の生成コードを変えない(ゴールデンテストで確認)ため、帯・近似曲線・注釈を使わない描画の経路は変わっていない。 diff --git a/tests/perf/bench.py b/tests/perf/bench.py index d041eb5..2f308c0 100644 --- a/tests/perf/bench.py +++ b/tests/perf/bench.py @@ -19,7 +19,7 @@ sys.path.insert(0, str(REPO / "tests" / "e2e")) from helpers import ( # noqa: E402 add_series_with_source, enter_edit_mode, image_generation, load_fixture, paste_text, plot_src, - open_tick_group, set_axis_option, set_errorbars, set_save_dpi, wait_app_ready, wait_copy_state, wait_data_ready, wait_latin_state, + add_annotation, add_fit, set_fill, open_tick_group, set_axis_option, set_errorbars, set_save_dpi, wait_app_ready, wait_copy_state, wait_data_ready, wait_latin_state, wait_plot_changed, ) from server import start_server # noqa: E402 @@ -501,6 +501,46 @@ def bench_ticks_change(browser, url, reps, csv_path): return out +# --- Phase 5b: 塗りつぶし帯・近似曲線・注釈 --- +def make_band_csv(path, rows=10_000): + """X + Y 5列 + 帯の下端 5列 + 帯の上端 5列 = 16 列。""" + import math + with open(path, "w", newline="", encoding="utf-8") as f: + w = csv.writer(f) + w.writerow(["x"] + [f"y{k + 1}" for k in range(5)] + [f"lo{k + 1}" for k in range(5)] + [f"hi{k + 1}" for k in range(5)]) + for i in range(rows): + x = i * 0.01 + ys = [math.sin(x * (k + 1)) + 0.1 * k for k in range(5)] + w.writerow([round(x, 4)] + [round(y, 5) for y in ys] + [round(y - 0.2, 5) for y in ys] + [round(y + 0.2, 5) for y in ys]) + + +def bench_p5b_change(browser, url, reps, band_path): + """5 系列すべてに塗りつぶし帯(下端 列6-10、上端 列11-15)と1次の近似曲線(凡例)を付け、注釈3つ(水平線・縦の帯・文字)を置き、 + data-summary に帯 5・近似線 5・注釈が出るまで待ってから、既存の「設定変更」と同じ方法で測る。""" + out = [] + ctx = _warm_context(browser, url, band_path) + for i in range(reps): + page = _prepared_page(ctx, url, band_path) + ids = page.evaluate("[...document.querySelectorAll('#seriesList .series-item')].map(e => e.querySelector('.series-y').id.match(/^series-(.+)-y$/)[1])") + assert len(ids) == 5, ids + for k, sid in enumerate(ids): + set_fill(page, sid, lower=f"__idx__{k + 6}", upper=f"__idx__{k + 11}") + add_fit(page, series=sid) + add_annotation(page, "hline", y="0.5") + add_annotation(page, "vspan", start="20", end="30") + add_annotation(page, "text", text="bench", x="50", y="1") + page.wait_for_function( + """() => { const d = document.querySelector('#plotArea img'); if (!d || !d.dataset.summary) return false; + try { const s = JSON.parse(d.dataset.summary)[0], a = s.annotations; + return s.bands >= 5 && s.fitlines >= 5 && a.hlines >= 1 && a.vspans >= 1 && a.texts >= 1; } catch (e) { return false; } }""", + timeout=TIMEOUT) + page.wait_for_timeout(3000) + out.append(page.evaluate(CHANGE_JS, ["#title", f"bench title {i}"])) + page.close() + ctx.close() + return out + + def fmt(name, xs): s = stats(xs) return f"{name:<44} median {s['median']:9.0f} min {s['min']:9.0f} max {s['max']:9.0f} (ms, n={s['n']})" @@ -511,7 +551,7 @@ def main(): ap.add_argument("--reps", type=int, default=5) ap.add_argument("--headed", action="store_true") ap.add_argument("--json") - ap.add_argument("--only", choices=["old", "new", "p5a"], help="old: Phase 3 までの項目だけ / new: Phase 4 の項目だけ / p5a: Phase 5a の項目だけ(省略時は全部)") + ap.add_argument("--only", choices=["old", "new", "p5a", "p5b"], help="old: Phase 3 までの項目だけ / new: Phase 4 の項目だけ / p5a: Phase 5a の項目だけ / p5b: Phase 5b の項目だけ(省略時は全部)") a = ap.parse_args() serve = Path(os.environ.get("E2E_SERVE_DIR") or REPO) srv, url = start_server(serve) @@ -526,6 +566,8 @@ def main(): make_datetime_csv(dt_path) eb_path = tmp / "bench_errorbars_10000x11.csv" make_errorbar_csv(eb_path) + band_path = tmp / "bench_bands_10000x16.csv" + make_band_csv(band_path) big_tsv = make_tsv() small_tsv = make_tsv(rows=30, ys=2) with sync_playwright() as p: @@ -584,6 +626,13 @@ def main(): "ticks_change_to_plot_ms": tk_change, "ticks_change_to_plot_minus_debounce_ms": [c - DEBOUNCE_MS for c in tk_change], }) + if a.only in (None, "p5b"): + b_change = bench_p5b_change(browser, url, a.reps, band_path) + res.update({ + # Phase 5b で追加(帯・近似曲線・注釈を付けた設定変更。デバウンス込みと、250 ms を除いた値) + "p5b_change_to_plot_ms": b_change, + "p5b_change_to_plot_minus_debounce_ms": [c - DEBOUNCE_MS for c in b_change], + }) browser.close() for k, v in res.items(): print(fmt(k, v)) From 4447cb20aad908d47cc54945dae29b542abfa3e8 Mon Sep 17 00:00:00 2001 From: mioupa <79833278+mioupa@users.noreply.github.com> Date: Tue, 10 Nov 2026 18:32:06 +0900 Subject: [PATCH 6/6] Document Phase 5b (series style, annotations, fits) in AGENTS.md and README Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 62 +++++++++++++++++++++++++++++++++++++------------------ README.md | 5 ++++- 2 files changed, 46 insertions(+), 21 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index fce69e5..b4770c5 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,7 +1,7 @@ # matplotlib GUI 引き継ぎ資料(AI エージェント向け) 要件の正は `docs/REQUIREMENTS.md`。このファイルと食い違う場合は REQUIREMENTS.md を優先する。 -この資料は Phase 5a(グラフ表現: エラーバー・目盛の詳細・枠線・日時の X の範囲。Phase 4 のデータ取り込みを含む)完了時点の実装を説明する。各 Phase の完了時に実装に合わせて更新すること(要件 A11)。 +この資料は Phase 5b(グラフ表現の続き: 系列のスタイル・注釈・近似曲線。5a のエラーバー・目盛の詳細・枠線・日時の X の範囲と、Phase 4 のデータ取り込みを含む)完了時点の実装を説明する。各 Phase の完了時に実装に合わせて更新すること(要件 A11)。 ## 1. ゴールと前提 @@ -16,7 +16,8 @@ - 保存 DPI(既定 300)、図サイズの単位(inch / cm / mm)、欧文フォント、スタイルプリセット、カラーパレット、クリップボードへのコピー、数式(mathtext)の案内が加わった。いずれも設定 → 生成コード → 実行の1本の経路に載る(GUI だけの特別扱いは無い)。 - Phase 4 でデータの取り込みが広がった。ファイルのドラッグ&ドロップ(ページ全体)と表の貼り付け(`pasted_data.tsv` として扱う)、`.tsv`、xlsx のシート選択、ヘッダより前に読み飛ばす行数、桁区切り・小数点・コメント記号、日時の列の自動認識と日時軸(X 軸の表示書式)、複数ファイル(最大10個。系列ごとにデータ元を選ぶ)。読込の引数は、生成コードの読込部にすべて明記する(区切り文字などの自動判定は足していない)。いずれも設定 → 生成コード → 実行の1本の経路に載る。 - CDN の URL はすべてバージョン固定にする。`tests/unit/test_cdn_pinning.py` が `index.html`・`js/`・`css/`・`py/` の全 URL を走査して強制する。取得しない説明リンクの `matplotlib.org` は、バージョンを含むパス(`/3.10.8/...`)だけ許可する。 -- Phase 5a でグラフの表現が広がった(PR 5a。G1・G2)。系列ごとのエラーバー(Y・X 方向、固定値か列、上下で別の値も可。端の長さ)、軸ごと(X / Y / 第2Y)の目盛の詳細(主目盛の間隔、副目盛の表示・なし・分割数、ラベルの書式、軸の反転)、上と右の枠線の切替、X が日時の列のときの X 軸の日時の範囲(`axes.x.dateMin` / `dateMax`)。画面で隠した設定は図に使わない(値は残る。要件 §2.2)。いずれも設定 → 生成コード → 実行の1本の経路に載り、設定が既定のときの生成コードは Phase 4 と1文字も変わらない(ゴールデンテストで確認)。注釈・近似曲線・式の列などは 5b 以降(`docs/REQUIREMENTS.md`)。 +- Phase 5a でグラフの表現が広がった(PR 5a。G1・G2)。系列ごとのエラーバー(Y・X 方向、固定値か列、上下で別の値も可。端の長さ)、軸ごと(X / Y / 第2Y)の目盛の詳細(主目盛の間隔、副目盛の表示・なし・分割数、ラベルの書式、軸の反転)、上と右の枠線の切替、X が日時の列のときの X 軸の日時の範囲(`axes.x.dateMin` / `dateMax`)。画面で隠した設定は図に使わない(値は残る。要件 §2.2)。いずれも設定 → 生成コード → 実行の1本の経路に載り、設定が既定のときの生成コードは Phase 4 と1文字も変わらない(ゴールデンテストで確認)。注釈・近似曲線は 5b で入った(次の項目)。 +- Phase 5b でグラフの表現がさらに広がった(PR 5b。G3・G4・G5)。系列のスタイル(点の形、不透明度、2列の間を塗りつぶす帯、系列の並べ替え(↑ ↓)と複製)、注釈(文字・水平線・垂直線・横の帯・縦の帯。最大 50 個)、近似曲線(系列ごとの1次式・多項式。式と R² を凡例か図の中に出せる。最大 20 本)と、それらを置く左パネルの「注釈・解析」の区分(`#sectionAnalysis`)。画面で隠した設定は図に使わない(要件 §2.2)。いずれも設定 → 生成コード → 実行の1本の経路に載り、設定が既定のときの生成コードは Phase 4 と1文字も変わらない(ゴールデンテストで確認。スキーマは version 4 のまま)。式の列(G6)などは 5c 以降(`docs/REQUIREMENTS.md`)。 ## 2. ファイル構成 @@ -26,13 +27,13 @@ | `pyscript.toml` | PyScript 設定(パッケージ、`packages_cache`、`[files]` による Python ファイルの配置) | | `css/style.css` | スタイル | | `js/main.js` | エントリ。UI を設定オブジェクトに結び付ける | -| `js/defaults.js` | 設定の既定値(`DEFAULT_SETTINGS`、`SCHEMA_VERSION` = 4)、UD カラーの色(`PALETTE`) | +| `js/defaults.js` | 設定の既定値(`DEFAULT_SETTINGS`、`SCHEMA_VERSION` = 4)、UD カラーの色(`PALETTE`)。Phase 5b: `DEFAULT_SERIES` に `marker` / `alpha` / `fill`、`DEFAULT_ANNOTATION` / `DEFAULT_FIT`(要素 1 つの既定値)、`DEFAULT_SETTINGS` に `annotations: []` / `fits: []` | | `js/units.js` | 図サイズの単位(`UNITS`、`UNIT_NAMES`、`UNIT_STEP`)と換算 `convertLength(value, from, to)`(mm を介し、to の単位で丸める: in 3 桁 / cm 2 桁 / mm 1 桁)。純粋な ES module | | `js/palettes.js` | カラーパレット(`PALETTES`: `ud` / `tab10` / `gray`)、`getPalette`、`paletteColor(id, index)`。id は `settings.PALETTES` と一致させる。色は JS だけが持つ | | `js/presets.js` | スタイルプリセット(`PRESETS`: standard / paper1 / paper2 / slide)、`planPreset`(適用内容を計算するだけ)、`newSeriesDefaults`(直前のプリセットを新しい系列へ)。名前は設定に入れない | | `js/code-state.js` | Pythonコードタブの状態(モード `sync` / `edit`、直近に生成したコードとその世代、「最新でない」印 `isCodeStale` / `setCodeStale`)。設定オブジェクトには入れない | -| `js/state.js` | 設定オブジェクトの保持・更新・購読(`getSettings`、`setPath`、`updateSeries`、`addSeries`、`removeSeries`、`applyPalette`、`setFileSheet`、`setLastPreset` / `getLastPreset`、`subscribe`、`toJson`)。直近に適用したプリセットはセッション中だけここに持つ | -| `js/bridge.js` | Python(`window.mplgui`)の唯一の窓口。読込・描画・保存・コピー(`makeClipboardImage`)・コードだけの更新(`script`)の制御、世代管理、日本語・欧文フォント取得の起動と待ち。読み込んだファイル(データN)ごとの状態(`File`・バイト列・貼り付けか・`loading` / `ready` / `error`・結果)を持ち、ファイルの追加・置き換え・削除(`selectFiles` / `selectFile` / `removeFile`)、読込の予約(`scheduleLoad`。ファイルごと)、最後のファイルを外したときの初期状態への復帰、コードの「最新でない」印を扱う | +| `js/state.js` | 設定オブジェクトの保持・更新・購読(`getSettings`、`setPath`、`updateSeries`、`addSeries`、`removeSeries`、`applyPalette`、`setFileSheet`、`setLastPreset` / `getLastPreset`、`subscribe`、`toJson`)。直近に適用したプリセットはセッション中だけここに持つ。Phase 5b: `moveSeries(id, delta)`、`duplicateSeries(id)`(全設定を写し、id と色(現在のパレットの未使用の色)だけ新しくして直後に入れる。近似曲線は写さない)、`removeSeries(id)`(その系列の近似曲線も消し、消した本数を返す。系列が1つだけ・見つからないときは -1)、`addAnnotation` / `updateAnnotation` / `removeAnnotation`、`addFit` / `updateFit` / `removeFit`。注釈と近似曲線の id は連番(`a1`…、`f1`…)で、削除しても再利用しない。通知の `kind` は `annotation-list` / `annotation-field` / `fit-list` / `fit-field`(一覧の変更とフィールドの変更)。`removeSeries` で近似曲線が消えたときは `series-list` に続けて `fit-list` を通知する | +| `js/bridge.js` | Python(`window.mplgui`)の唯一の窓口。読込・描画・保存・コピー(`makeClipboardImage`)・コードだけの更新(`script`)の制御、世代管理、日本語・欧文フォント取得の起動と待ち。読み込んだファイル(データN)ごとの状態(`File`・バイト列・貼り付けか・`loading` / `ready` / `error`・結果)を持ち、ファイルの追加・置き換え・削除(`selectFiles` / `selectFile` / `removeFile`)、読込の予約(`scheduleLoad`。ファイルごと)、最後のファイルを外したときの初期状態への復帰、コードの「最新でない」印を扱う。Phase 5b: `addNote(message)`(画面の操作の注意を、次の描画結果の警告に1度だけ添える。系列の削除で近似曲線が消えたとき、データ元の変更・列の消失で帯の列を戻したときに使う) | | `js/startup-progress.js` | Python 起動中の段階表示。Resource Timing(`PerformanceObserver`、取得済みエントリを含む)から Pyodide 本体(`pyodide.asm.wasm`・`python_stdlib.zip`)→ パッケージ wheel(pandas / matplotlib)→ 初期化(`/py/main.py` の取得)を推定する | | `js/font-cache.js` | フォントの取得と Cache Storage への保存。種類(`japanese` / `arimo` / `tinos`)ごとの URL(`FONT_URLS`)、種類ごとに1セッション1回の取得、旧 OTF のキャッシュ削除 | | `js/ui/codeTab.js` | Pythonコードタブ(行番号、モード別のボタン、コピー、.py 保存、Ctrl/Cmd+Enter) | @@ -42,25 +43,27 @@ | `js/ui/fileList.js` | 2ファイル以上のときのファイル一覧(`#fileList`。各行 `file-`・シートの選択・削除)と、データ確認タブの表示元の切替(`#previewSource`)。`bridge.js` が作る表示用のデータを描くだけ | | `js/ui/dateFormat.js` | 軸・目盛区分の X 軸の日時の書式(`#xDateFormat` のプリセットと「任意」の `#xDateFormatCustom`)。値は `axes.x.dateFormat` に書く。表示の可否(`#xDateFormatGroup`)は `series.js` が決める | | `js/ui/axisTicks.js` | 軸・目盛区分の、目盛の入力欄・日時の範囲(`#xDateRangeGroup`)・枠線の表示と無効の切り替え(`syncAxisTicks(xKind)`)。軸の種類(`number` / `log` / `datetime` / `category`)は渡された `xKind`(`series.js` の `xAxisKind`)と、Y / 第2Y のスケールで決める。値は消さない(隠すだけで、Python も使わない)。設定の値は `forms.js` が結ぶ | +| `js/ui/annotations.js` | 注釈のカード(`#annotationList`。`#addAnnotationBtn`)。カードは state の `annotations` から描き、種類ごとに使う入力欄だけを出す(`SHOWN`。Python の使う項目と同じ規則)。X の入力欄の例・補足は軸の種類(`series.js` の `xAxisKind`)で変える(数値 / 日時 / 文字列は何番目か)。`syncAnnotations`(入力中の欄を作り直さずに表示を同期する。`addVisibilityHook` に登録)、`renderAnnotationList`、`bindAnnotations` | +| `js/ui/fits.js` | 近似曲線のカード(`#fitList`。`#addFitBtn`)。系列の選択肢は `seriesDisplayName` で作り、系列の追加・削除・並べ替え・名前の変更に追従する。線の色は「系列の色」か「色を選ぶ」(`colorPickerHtml`)。棒グラフでは一覧と追加ボタンを隠して `#fitBarNote` を出す。`syncFits`(`addVisibilityHook` に登録。追加ボタンの上限による無効化も、注釈の分とあわせてここで行う)、`renderFitList`、`bindFits` | | `js/ui/panelSections.js` | 設定パネルの区分(`details.panel-section`)の折りたたみ。状態は localStorage(キー `mplgui.panelSections`、`{区分の id: 開いているか}`)だけに持ち、設定オブジェクトには入れない。localStorage が使えなくても動く(すべて開く) | | `js/ui/styleSection.js` | 体裁区分: プリセットの「適用」、カラーパレット、図サイズの単位切替(数値を換算し、ラベルと step を単位に合わせる) | | `js/ui/saveSection.js` | 保存区分: DPI(72 / 150 / 300 / 600 のセレクトと「任意」の入力欄)。値は `save.dpi`(数値)に書く | | `js/ui/clipboard.js` | 「クリップボードにコピー」。`` を更新する | -| `js/ui/*.js`(上記以外) | 画面部品(`colorPicker`、`dataPreview`(先頭100行、前置き行の枠、日時の列の印)、`fileInfo`(選択中のファイル名と文字コードの表示)、`forms`、`notify`、`plotView`(画像と `data-summary`)、`progress`、`saveFormat`(形式に応じた透過の可否と、SVG の文字・PDF の説明の出し分け)、`series`(系列カード。複数ファイルのときはデータ元の選択と、データ元ごとの列の選択肢。X の日時の列の有無)、`tabs`)。Phase 5a で `series`: 系列カードに折りたためる「エラーバー」(`.series-errorbars`。Y 方向・X 方向のブロックと端の長さ。開閉は系列 id ごとにセッション中だけ覚える)、`xAxisKind`(X 軸の種類を、列の `kind` / `numericLike` から Python と同じ規則で決める。export)、データ元を替えたとき誤差の列を空に戻す。`forms`: 目盛・日時の範囲・枠線の入力欄を `FIELDS` に足した | +| `js/ui/*.js`(上記以外) | 画面部品(`colorPicker`、`dataPreview`(先頭100行、前置き行の枠、日時の列の印)、`fileInfo`(選択中のファイル名と文字コードの表示)、`forms`、`notify`、`plotView`(画像と `data-summary`)、`progress`、`saveFormat`(形式に応じた透過の可否と、SVG の文字・PDF の説明の出し分け)、`series`(系列カード。複数ファイルのときはデータ元の選択と、データ元ごとの列の選択肢。X の日時の列の有無)、`tabs`)。Phase 5a で `series`: 系列カードに折りたためる「エラーバー」(`.series-errorbars`。Y 方向・X 方向のブロックと端の長さ。開閉は系列 id ごとにセッション中だけ覚える)、`xAxisKind`(X 軸の種類を、列の `kind` / `numericLike` から Python と同じ規則で決める。export)、データ元を替えたとき誤差の列を空に戻す。`forms`: 目盛・日時の範囲・枠線の入力欄を `FIELDS` に足した Phase 5b で `series`: 点の形・不透明度・塗りつぶし帯(`.series-fill`。開閉は系列 id ごとにセッション中だけ覚える)・↑ ↓・複製のコントロール、`seriesDisplayName(series)`(凡例名、無ければ Y 列の表示。export)、`addVisibilityHook(fn)`(`syncVisibility` の最後に呼ぶ関数を足す。注釈・近似曲線の同期を、循環 import なしで登録する)、データ元を替えたときと、列が無くなったとき(`reconcileColumns`)に帯の列を空に戻して `addNote` で知らせる。`colorPicker`: `colorPickerHtml(idBase, color, extraClass)`(系列以外のカードでも色の選択を使う)、色のパネルを閉じる処理を系列一覧だけでなくページ全体に広げた | | `py/main.py` | PyScript のエントリ。JS と `mplgui` の橋渡しだけを書く(`window.mplgui` の登録(`loadFile` / `removeSource` / `clearSources` / `render` / `save` / `copyImage` / `script` / `registerFont` など)、Excel 用ライブラリの遅延導入、作業フォルダ `api.SESSION.workdir` の設定) | -| `py/mplgui/settings.py` | 設定スキーマ(version 4)、既定値、検証、日本語エラー(凍結 dataclass へ変換。`FileEntry`、読込設定の検証、`axes.x.dateFormat`、目盛・枠線・日時の範囲・エラーバー)、`migrate_settings`(v1 → v2 → v3 → v4) | +| `py/mplgui/settings.py` | 設定スキーマ(version 4)、既定値、検証、日本語エラー(凍結 dataclass へ変換。`FileEntry`、読込設定の検証、`axes.x.dateFormat`、目盛・枠線・日時の範囲・エラーバー)、`migrate_settings`(v1 → v2 → v3 → v4)。Phase 5b: 系列の `marker` / `alpha` / `fill`(`FillSettings`)、`AnnotationSettings` / `FitSettings`(`Settings.annotations` / `fits`)、`default_annotation()` / `default_fit()`(JS の既定値と `test_defaults_parity.py` で比べる)、`_parse_fill` / `_parse_annotations` / `_parse_fits`。定数 `MAX_ANNOTATIONS`(50)・`MAX_FITS`(20)。`_number` / `_choice` に `field_name` を足した(`field` を表示名と別にできる) | | `py/mplgui/loader.py` | バイト列から DataFrame(文字コード判定、区切り文字、読込設定(`skip_lines` / `thousands` / `decimal` / `comment`)、xlsx のシート、日時の列の認識、プレビューと前置き行)。読込結果に `SourceInfo`(ファイル名、種別(csv / txt / tsv / xlsx)、文字コード、区切り文字、ヘッダの有無、読込設定、シート名とシート一覧、日時に変換した列 `datetime_columns`、貼り付けたデータか `pasted`)を付ける。`SourceInfo.read_kwargs()` が `pd.read_csv` / `pd.read_excel` の引数の唯一の定義で、loader と codegen が共有する。`split_lines`(pandas と同じく `\r` / `\n` / `\r\n` だけで行を分ける)、`detect_datetime_columns` / `convert_datetime` / `apply_datetime_columns`、`open_excel`(`pd.ExcelFile`)も持つ。Phase 5a: `columns[].numericLike`(`looks_numeric`: 文字列の列でも空欄以外の半数以上が数値に読めるか)を足した。`looks_numeric` / `is_blank_cell` は dataprep と共有する(X が文字列の列かの判定が画面と Python で一致する) | -| `py/mplgui/dataprep.py` | DataFrame(または `{ファイル id: DataFrame}`)を見て決める処理。`plan_plot` が描画計画 `PlotPlan` を作る(データ元ごとの `skipRows` と Y 列の自動割り当て、X の数値変換・日時・文字列の別、描ける点の有無、A7 の警告(桁区切り・小数点のヒント付き)、日時の X の検査、データ由来の日本語 `UserError`)。描画に使うデータ元は `PlotPlan.sources`(`PlanSource`: id・番号・変数名・ファイル名)と `SeriesPlan.data_id` / `data_var` に持つ。Phase 5a: `AxisPlan` / `AxesPlan`(軸ごとに効く目盛の設定だけ。軸の種類・主目盛の間隔・副目盛・書式・反転・日時の範囲)を `PlotPlan.axes` に持つ。`ErrorPlan`(`SeriesPlan.y_err` / `x_err`、`cap_size`)。目盛の本数の見積もり(`MAX_MAJOR_TICKS` = 100。超えると日本語の `UserError`)。X の数値の範囲の検査(`settings.check_axis_range`)は、X が日時でないときだけここで行う(日時のときは `validate_date_range`) | -| `py/mplgui/codegen.py` | 設定・`SourceInfo`(または `{ファイル id: SourceInfo}`)・`PlotPlan` から matplotlib スクリプトを生成する(`generate_script`)。純粋な関数。Phase 5a: 目盛・反転・日時の範囲は軸ごとの関数(`_axis_blocks` が Axes の変数名 `ax` / `ax2` を持つ `_AxisBlock` を作り、`_axis_tick_lines` などが変数名を引数で受ける)。枠線は `_emit_spines`。エラーバーは `draw_error_bars` の定義(使うときだけ冒頭に書く)と `_emit_line_error_bars`、棒グラフは `ax.bar` の `yerr` | +| `py/mplgui/dataprep.py` | DataFrame(または `{ファイル id: DataFrame}`)を見て決める処理。`plan_plot` が描画計画 `PlotPlan` を作る(データ元ごとの `skipRows` と Y 列の自動割り当て、X の数値変換・日時・文字列の別、描ける点の有無、A7 の警告(桁区切り・小数点のヒント付き)、日時の X の検査、データ由来の日本語 `UserError`)。描画に使うデータ元は `PlotPlan.sources`(`PlanSource`: id・番号・変数名・ファイル名)と `SeriesPlan.data_id` / `data_var` に持つ。Phase 5a: `AxisPlan` / `AxesPlan`(軸ごとに効く目盛の設定だけ。軸の種類・主目盛の間隔・副目盛・書式・反転・日時の範囲)を `PlotPlan.axes` に持つ。`ErrorPlan`(`SeriesPlan.y_err` / `x_err`、`cap_size`)。目盛の本数の見積もり(`MAX_MAJOR_TICKS` = 100。超えると日本語の `UserError`)。X の数値の範囲の検査(`settings.check_axis_range`)は、X が日時でないときだけここで行う(日時のときは `validate_date_range`)。Phase 5b: `FillPlan`(`SeriesPlan.fill`。帯の列番号・コメント用の列の表示・不透明度)、`SeriesPlan.marker` / `alpha`(`_marker_plan` が点の形と点サイズを決める)、`AnnotationPlan`(`PlotPlan.annotations`。位置を軸の種類で解釈した値。`_plan_annotations`)、`FitPlan`(`PlotPlan.fits`。`_build_fit_plans`、データの検査 `_check_fit_data`)。注釈の位置と帯の端の値は `_Extents` に足し、主目盛の本数の見積もりに含める | +| `py/mplgui/codegen.py` | 設定・`SourceInfo`(または `{ファイル id: SourceInfo}`)・`PlotPlan` から matplotlib スクリプトを生成する(`generate_script`)。純粋な関数。Phase 5a: 目盛・反転・日時の範囲は軸ごとの関数(`_axis_blocks` が Axes の変数名 `ax` / `ax2` を持つ `_AxisBlock` を作り、`_axis_tick_lines` などが変数名を引数で受ける)。枠線は `_emit_spines`。エラーバーは `draw_error_bars` の定義(使うときだけ冒頭に書く)と `_emit_line_error_bars`、棒グラフは `ax.bar` の `yerr`。Phase 5b: セクション番号の自動採番(`_Builder.section(title)` が呼んだ順に振る)、`_emit_annotations`(「注釈」節)、`_emit_band`、点の形・不透明度(`_alpha_arg`)、`_emit_fits` と `POLY_TEXT_FUNCTION`(`poly_text`)、凡例を出すかの判定に注釈の凡例名と近似曲線を含めた、手順(`Step`)に「系列Nの塗りつぶし帯」「注釈N」「近似曲線N」を足した | | `py/mplgui/formats.py` | 保存形式の表(`FORMATS`)、保存解像度の既定値(`DEFAULT_SAVE_DPI` = 300。実際の値は `save.dpi`)、`build_filename`、`savefig_kwargs`、形式ごとの rcParams(`savefig_rc`)、PNG / JPG の画素数の上限(`MAX_RASTER_PIXELS`、`MAX_RASTER_SIDE`、`raster_pixels`、`check_raster_size`)。runner と codegen が共有する | -| `py/mplgui/runner.py` | スクリプトの実行(`run_script` / `run_to_image`)、Figure → 画像(PNG/JPG/SVG/PDF。`savefig_rc` を `rc_context` で適用、画素数の検査)、図の要約(`figure_summary`)、実行時エラーの整形、数式の誤りの判定(`is_mathtext_error`、`MathtextError`)。`figure_summary` に、`yticklabels` / `xinverted` / `yinverted` / `spines` / `xmajor` / `ymajor` / `xminor` / `yminor` / `xformatter` / `yformatter` / `yoffset`(軸の端の ×10^n)/ `errorbars`(エラーバーの本数)を足した | +| `py/mplgui/runner.py` | スクリプトの実行(`run_script` / `run_to_image`)、Figure → 画像(PNG/JPG/SVG/PDF。`savefig_rc` を `rc_context` で適用、画素数の検査)、図の要約(`figure_summary`)、実行時エラーの整形、数式の誤りの判定(`is_mathtext_error`、`MathtextError`)。`figure_summary` に、`yticklabels` / `xinverted` / `yinverted` / `spines` / `xmajor` / `ymajor` / `xminor` / `yminor` / `xformatter` / `yformatter` / `yoffset`(軸の端の ×10^n)/ `errorbars`(エラーバーの本数)を足した。Phase 5b: `figure_summary` に `bands` / `markers` / `alphas` / `annotations`(`texts` / `hlines` / `vlines` / `hspans` / `vspans`)/ `fitlines` / `fittexts` を足した(`_style_summary`。§4) | | `py/mplgui/fonts.py` | フォントの登録と rcParams。日本語の一覧 `SANS_SERIF_PRIORITY`(先頭は Noto Sans JP)と、欧文フォントの表 `LATIN_FONTS`(Arimo / Tinos の表示名・候補名・mathtext フォントセット)が唯一の定義で、生成スクリプトもこれを使う。`register_font_bytes(data, kind=)` は種類(`japanese` / `arimo` / `tinos`)ごとに1回だけ登録する | | `py/mplgui/errors.py` | `UserError`(利用者が直せるエラー) | | `py/mplgui/api.py` | JS から呼ばれる JSON 入出力の関数(`render_json` / `save_json` / `copy_image_json` / `script_json` など)。読込済みデータ(`SESSION`。ファイル id ごとの `LoadedSource`(`df`・`SourceInfo`・書き出したファイル)と、xlsx の `ExcelFile` のキャッシュ(同じバイト列の間だけ)。`remove_source_json` / `clear_sources_json` も持つ)と、アップロードしたファイルの作業フォルダへの書き出しを持つ | | `py/mplgui/runtime.py` | 警告フィルタ(起動時) | -| `tests/unit/` | 単体テスト(CPython、Agg)。`test_js_modules.py` は node で純粋な JS モジュール(units / palettes / presets / state)を検査する | -| `tests/e2e/` | E2E テスト(pytest-playwright、Chromium)。`run_script_summary.py` は、生成スクリプトを CPython で実行して図の要約を出す補助(一致確認用)。Phase 5a: `test_ticks.py`・`test_errorbars.py`・`test_codegen_consistency.py` が増えた | -| `tests/fixtures/` | 合成テストデータ(`make_fixtures.py` が生成。説明は `README.md`。Phase 4 で `preamble` / `european` / `thousands` / `comments` / `datetime` / `datetime_iso_tz` / `dates_ja` などを追加)。Phase 5a で `errorbars.csv`(エラーバー用)を追加 | +| `tests/unit/` | 単体テスト(CPython、Agg)。`test_js_modules.py` は node で純粋な JS モジュール(units / palettes / presets / state)を検査する。Phase 5b: `test_series_style.py`・`test_annotations.py`・`test_fits.py`、共通の補助 `style_helpers.py` が増えた | +| `tests/e2e/` | E2E テスト(pytest-playwright、Chromium)。`run_script_summary.py` は、生成スクリプトを CPython で実行して図の要約を出す補助(一致確認用)。Phase 5a: `test_ticks.py`・`test_errorbars.py`・`test_codegen_consistency.py` が増えた。Phase 5b: `test_series_style.py`・`test_annotations.py`・`test_fits.py` が増えた | +| `tests/fixtures/` | 合成テストデータ(`make_fixtures.py` が生成。説明は `README.md`。Phase 4 で `preamble` / `european` / `thousands` / `comments` / `datetime` / `datetime_iso_tz` / `dates_ja` などを追加)。Phase 5a で `errorbars.csv`(エラーバー用)を追加 Phase 5b で `band.csv`(帯・近似曲線・注釈用)を追加 | | `tests/unit/golden/`、`tests/unit/golden_cases.py` | Phase 4 のコードで生成した既定の設定の出力(`*.py.txt`)と、その構成の定義。`test_codegen_compat.py` が、既定の設定の生成コードが Phase 4 と1文字も変わらないことを確かめる(line / scatter / bar / 対数 / 日時 / 文字列の X / 2ファイル) | | `tests/perf/bench.py` | 起動・描画の計測。結果は `docs/PERFORMANCE.md` | | `.github/workflows/tests.yml` | CI | @@ -73,7 +76,7 @@ - スキーマのバージョンは 4(`version`)。JSON のキーは camelCase。 - 唯一の正は JS 側(`js/state.js`)の設定オブジェクト。Python は DOM を読まず、渡された JSON を `settings.parse_settings` / `parse_load_settings` で凍結 dataclass に変換して使う。 - JS の既定値(`js/defaults.js`)と Python の既定値(`settings.default_settings()`)は一致させる。`tests/unit/test_defaults_parity.py` が比較する(node が無いと skip)。 -- 主な構造: `load`(`delimiter`、`hasHeader`、`skipLines`、`thousands`、`decimal`、`comment`、`parseDates`、`files`)、`plot`(`type`、`skipRows`、`xColumn`、`title`、`fontSize`、`figure`、`latinFont`、`palette`、`legend`、`grid`、`margins`)、`axes`(`x` / `y` / `y2`: `label`、`scale`、`min`、`max`。`x` だけ `dateFormat`)、`series[]`、`save`(`filename`、`format`、`transparent`、`dpi`、`svgText`)。 +- 主な構造: `load`(`delimiter`、`hasHeader`、`skipLines`、`thousands`、`decimal`、`comment`、`parseDates`、`files`)、`plot`(`type`、`skipRows`、`xColumn`、`title`、`fontSize`、`figure`、`latinFont`、`palette`、`legend`、`grid`、`margins`)、`axes`(`x` / `y` / `y2`: `label`、`scale`、`min`、`max`。`x` だけ `dateFormat`)、`series[]`、`annotations[]`、`fits[]`、`save`(`filename`、`format`、`transparent`、`dpi`、`svgText`)。 - Phase 3 で足した項目と既定値: - `plot.figure`: `{width: 8, height: 6, unit: "in"}`。`unit` は `in` / `cm` / `mm`。`width` / `height` は選んだ単位の値で持つ(インチに直して持たない)。Python が検証するときだけ `FigureSettings.width_in` で「値 / 1インチあたりの長さ(2.54 / 25.4)」と割ってインチにする。上限は 50 inch を選んだ単位に直した値(in 50 / cm 127 / mm 1270)で、超えると単位つきの日本語エラー。 - `plot.latinFont`: `default` / `arimo` / `tinos`(既定 `default`)。`plot.palette`: `ud` / `tab10` / `gray`(既定 `ud`。Python は選択肢の検証だけで、色は JS の `palettes.js` が持つ)。 @@ -91,8 +94,13 @@ - 隠れている項目は検証せず使わない(要件 §2.2): 対数軸の `majorStep`、`minorTicks` が `on` でないときの `minorDivisions`、`tickFormat` が `fixed` / `sci` でないときの `tickDecimals`、使っていない第2Y軸の目盛の項目すべて(`_parse_axis(ticks=False)`)。X が日時のときの `dateMin` / `dateMax` の検証と、X が日時でないときの X の数値の範囲(`min` / `max`)の検査は、軸の種類が分かる dataprep が行う(settings は日時の範囲を寛容に正規化するだけ。Y・第2Y の範囲は従来どおり settings が検査)。日時と文字列の X の `majorStep` は整数(`MAX_MAJOR_TICKS` は §4.1)。 - `plot.spines`(`{top: true, right: true}`): 上・右の枠線の表示。第2Y軸があるときの右の枠線(第2Y軸の線)は消せない(画面は無効にし、Python も使わない)。 - `series[].errorBars`(`{y: E, x: E, capSize: 3}`。`E = {mode: "none", symmetric: true, value: null, valueMinus: null, column: "", columnMinus: ""}`): `mode` は `none` / `fixed`(固定値)/ `column`(列)。`value` / `valueMinus`(上(右)・下(左))は 0 以上の数。`fixed` では必須(`symmetric` が false なら両方)。`column` / `columnMinus` は `__idx__N` だけ(`column` では必須)。`capSize` は 0〜50(pt)。誤りは「系列NのY誤差(上)の値」などの日本語エラー(`field` も同じ)。棒グラフでは X 方向を使わない(隠れているので検証しない)。`mode` が `none` の方向は、ほかの項目を検証しない。 +- Phase 5b で足した項目と既定値(スキーマは version 4 のまま。新しい項目は既定値で補われ、図は 5a と同じ。JS の `DEFAULT_SERIES` / `DEFAULT_ANNOTATION` / `DEFAULT_FIT` と Python の `default_settings()` / `default_annotation()` / `default_fit()` は一致させる): + - `series[]`: `marker`(`auto`。`auto` / `none` / `o` / `s` / `^` / `v` / `D` / `x` / `+` / `*`)、`alpha`(1。0〜1。棒グラフでも使う)、`fill`(`{lower: "", upper: "", alpha: 0.25}`。`lower` / `upper` は `__idx__N` だけ。両方空なら帯なしで、`alpha` は検証しない。片方だけは「系列Nの塗りつぶし帯」の日本語エラー)。棒グラフでは `marker` と `fill` を隠すので、検証せず使わない。scatter で `marker` が `none` は「系列Nの点の形」のエラー(点が見えなくなるため)。誤りの `field` は「系列Nの点の形」「系列Nの不透明度」「系列Nの塗りつぶし帯」。line の点は、`auto` なら従来どおり(点サイズが 0 より大きいときだけ丸)、形を選んで点サイズが自動なら面積 24(scatter と同じ)、`none` なら点サイズを使わない(画面は点サイズ欄を無効にする)。scatter の `auto` は `marker=` を書かない。 + - `annotations[]`(既定は空。上限 `MAX_ANNOTATIONS` = 50。超えると「注釈は50個までです。」): `{id, kind, text, x, y, start, end, coords, axis, color, lineStyle, lineWidth, alpha, fontSize, label}`。`kind` は `text` / `hline` / `vline` / `hspan` / `vspan`。`id` は `a1`、`a2`、…(JS が払い出し、削除しても再利用しない。Python は重複・空なら振り直す)。`coords` は `text` だけ(`data` / `axes`)。`axis`(`y` / `y2`)は Y を使う種類(`hline` / `hspan` / データ座標の `text`)で第2Y軸を使うときだけ検証して使う(そうでなければ第1Y軸)。`alpha: null` は自動(帯 0.2、それ以外 1)、`fontSize: null` は図のフォントサイズ。`text` は 200 文字まで。種類で使わない項目は、検証せず既定値にする(隠れた不正な値で描画を止めない)。位置(`x` / `y` / `start` / `end`)は文字列のまま持ち(数値は文字列にする)、軸の種類で解釈するのは dataprep(下記)。誤りの `field` は「注釈Nの種類」「注釈Nの文字」「注釈Nの座標」「注釈Nの色」「注釈Nの不透明度」「注釈Nの線種」「注釈Nの線幅」「注釈Nの文字の大きさ」「注釈Nの軸」「注釈Nの開始」「注釈Nの終了」。X・Y の位置は「注釈NのX」「注釈NのY」(空白なし。dataprep が出す)。 + - 位置の解釈(`dataprep._annotation_value`。軸の種類は `xAxisKind` と同じ規則): 数値の軸は数、対数軸は 0 より大きい数(Y は `axes.y` / `axes.y2` の `scale`、X は X 軸の種類)、日時の X は年が先頭の日付・日時(`_date_range_value` で正規化した文字列。コードでは `pd.Timestamp(...)`)、文字列の X と棒グラフの X は「何番目のカテゴリか」の数(0 始まり。1.5 なら 2 つ目と 3 つ目の間)、`text` の `coords: axes` は X・Y とも数(図の割合 0〜1)。日時の X に日付でない値、数値の軸に日付、未入力、`text` の文字が空、はいずれも日本語の `UserError`。注釈の位置は主目盛の本数の見積もりにも含める。 + - `fits[]`(既定は空。上限 `MAX_FITS` = 20。超えると「近似曲線は20本までです。」): `{id, series, model, degree, show, color, lineStyle}`。`id` は `f1`、`f2`、…(注釈と同じ規則)。`series` は系列の id(無いと「近似曲線Nの系列」の日本語エラー。JS は追加時に先頭の系列にする)、`model` は `linear` / `poly`、`degree` は 2〜6 の整数(既定 2。`linear` では隠れるので検証せず 1 にする)、`show` は `legend` / `text` / `none`(式と R² を出す先)、`color` は `""` なら系列の色、`lineStyle` は `dashed`。棒グラフでは近似曲線を隠すので、検証せず使わない。データ由来の検査は dataprep: X が日時・文字列の系列、X の異なる値が次数 + 1 個未満、Y がすべて同じ(R² を計算できない)、描ける点が無い系列は、いずれも「近似曲線N: …」(`field` は「近似曲線Nの系列」)。系列を削除すると、その系列の近似曲線も消える(JS の `removeSeries`)。 - パレットの色、プリセットの値、単位の換算は JS だけが持つ(`js/palettes.js`、`js/presets.js`、`js/units.js`)。プリセット名は設定に入れない。「適用」は図サイズ・単位・フォントサイズ・各系列の線幅と点サイズを個別の設定に書き込むだけで、直近のプリセットは `state.js` がセッション中だけ覚える(新しい系列に、線幅と、scatter のときの点サイズを引き継ぐ)。点サイズは、プリセットが自動(標準)なら全系列を自動に戻し、数値なら scatter か点サイズを入力済みの系列だけ書き換える。パレットの切替(`state.applyPalette`)は、全系列を系列の順に新しいパレットの色で塗り直してから `plot.palette` を書く。新しい系列の既定色は現在のパレットの未使用色。 -- 系列: `id`、`x`、`y`、`color`、`lineWidth`、`lineStyle`、`markerSize`、`label`、`secondaryAxis`、`source`、`errorBars`(Phase 5a)。`markerSize: null` は「自動」(line は 0、scatter は 24)。ユーザーが数値を入れたら自動切替の対象外。 +- 系列: `id`、`x`、`y`、`color`、`lineWidth`、`lineStyle`、`markerSize`、`label`、`secondaryAxis`、`source`、`errorBars`(Phase 5a)、`marker` / `alpha` / `fill`(Phase 5b)。`markerSize: null` は「自動」(line は 0、scatter は 24)。ユーザーが数値を入れたら自動切替の対象外。 - Pythonコードタブの状態(モード `sync` / `edit`、生成したコード)は設定オブジェクトに入れず、`js/code-state.js` に持つ。編集モードのコード本文は、`render` / `save` の別引数 `code` で渡す。「使用する」(`useCustomCode`)は廃止した。 ## 4. Python ⇄ JS の API(`window.mplgui`) @@ -115,7 +123,8 @@ Python が登録し、登録後に `mplgui-ready` イベントを送る。引数 `defaultCustomCode()` は廃止した(Phase 2)。 -- `code` が null(GUI 同期): 設定から生成したスクリプトの「自動描画用」(§4.1)を、読込済みの DataFrame(`df`)を渡して実行する。`image` は PNG の data URI、`code` は表示用の完全なスクリプト、`output` は実行中の print / stderr、`summary` は `runner.figure_summary` の軸ごとの要約(Phase 5a で、`yticklabels`・`xinverted` / `yinverted`・`spines`(top / right)・`xmajor` / `ymajor` / `xminor` / `yminor`(ロケータのクラス名)・`xformatter` / `yformatter`・`yoffset`(軸の端の ×10^n)・`errorbars`(エラーバーの本数。`_errorbar` ラベルの線と `ErrorbarContainer`)を足した)。読込済みデータが必要。`save` は保存設定の形式・背景透過・`save.dpi`・`save.svgText` で書き出す(`render` のプレビューは dpi 100、`PREVIEW_DPI`)。形式ごとの rcParams(`formats.savefig_rc`: PDF は `pdf.fonttype=42`、SVG は `svg.fonttype` = `path` / `none`)は `matplotlib.rc_context` で `savefig` の間だけ適用する(生成コードの `plt.rcParams[...]` と同じ値)。`copyImage` は保存形式にかかわらず PNG を `save.dpi` で作り、背景透過は保存設定に従う(クリップボードにコピーする画像。C5)。`script` は、保存設定(`save.*`)の変更で表示中のコードだけを作り直すのに使う(§5)。 +- `code` が null(GUI 同期): 設定から生成したスクリプトの「自動描画用」(§4.1)を、読込済みの DataFrame(`df`)を渡して実行する。`image` は PNG の data URI、`code` は表示用の完全なスクリプト、`output` は実行中の print / stderr、`summary` は `runner.figure_summary` の軸ごとの要約(Phase 5a で、`yticklabels`・`xinverted` / `yinverted`・`spines`(top / right)・`xmajor` / `ymajor` / `xminor` / `yminor`(ロケータのクラス名)・`xformatter` / `yformatter`・`yoffset`(軸の端の ×10^n)・`errorbars`(エラーバーの本数。`_errorbar` ラベルの線と `ErrorbarContainer`)を足した。Phase 5b で、`bands`(塗りつぶし帯の数。ラベル `_fill` の collection)・`markers`(系列の線の `get_marker()` の文字列。点なしは `"None"`)・`alphas`(系列の線の alpha に、続けて scatter の alpha。未指定は `null`)・`annotations`(`{texts, hlines, vlines, hspans, vspans}`)・`fitlines` / `fittexts`(近似曲線の線と式の文字の数)を足した。既存のキーの値は変えない)。読込済みデータが必要。`save` は保存設定の形式・背景透過・`save.dpi`・`save.svgText` で書き出す(`render` のプレビューは dpi 100、`PREVIEW_DPI`)。形式ごとの rcParams(`formats.savefig_rc`: PDF は `pdf.fonttype=42`、SVG は `svg.fonttype` = `path` / `none`)は `matplotlib.rc_context` で `savefig` の間だけ適用する(生成コードの `plt.rcParams[...]` と同じ値)。`copyImage` は保存形式にかかわらず PNG を `save.dpi` で作り、背景透過は保存設定に従う(クリップボードにコピーする画像。C5)。`script` は、保存設定(`save.*`)の変更で表示中のコードだけを作り直すのに使う(§5)。 +- `figure_summary` の 5b のキーの数え方と注意(`runner._style_summary`): 線は `transform` で分ける(`axhline` は Y だけ、`axvline` は X だけデータ座標。両方データ座標の線が系列の線)。`markers` / `alphas` の線は、エラーバー(`_errorbar`)・近似曲線・注釈の線を除いた系列の線だけ。近似曲線の線は、ラベルが `_fit` か `$R^2$ = ` を含む線。近似曲線の式の文字は、`y = ` と `$R^2$ = ` を両方含む文字として判定する(同じ並びを含む利用者の注釈の文字は、式として数えてしまう)。`annotations.texts` は `ax.texts` から式の文字を引いた数で、図の中の割合で置いた文字も含む。`hspans` / `vspans` は `ax.patches` を `transform` で数える(棒グラフの棒は数えない)。 - `code` が文字列(編集モード。`save` / `copyImage` も同様): そのスクリプトを丸ごと、アップロードしたファイルのある作業フォルダ(`SESSION.workdir`)で実行する。`render` は設定を読まない(設定が不正でも、読込済みデータが無くても動く)。`save` は保存設定(`save.*`)だけを `settings.parse_save_settings` で検証して使う(描画設定が不正でも、編集したコードの図は保存できる)。GUI の設定をコードの結果に上書き適用することはしない(A8)。 - `loadFile` は、読み込んだファイルを元のファイル名(フォルダ部分は除く)で作業フォルダに書き出す(同じ id の前のファイルは消す。失敗したらその id の読込済みデータと書き出したファイルを破棄する)。貼り付けたデータは `pasted_data.tsv`(UTF-8、タブ区切り)という名前のファイルとして同じ経路で読む。こうして、表示中のスクリプトの `pd.read_csv("ファイル名", ...)` がそのまま動く(P5)。 - 読込の規則(`loader.load_file`): 拡張子は `.csv` / `.txt` / `.tsv` / `.xlsx`(それ以外は「対応していない拡張子です。xlsx/csv/txt/tsvを選択してください。」)。区切り文字の既定は拡張子で決まる(csv はカンマ、txt は空白、tsv はタブ。自動判定はしない)。pandas に渡す引数は `SourceInfo.read_kwargs()`(csv: `sep`・`header`・`skiprows`・`thousands`・`decimal`・`comment`・`engine="python"`。xlsx: `sheet_name`・`header`・`skiprows`・`thousands`・`decimal`・`comment`)。xlsx のシートは `loadJson` の `load.files` のうち `sourceId` の項目から決め(無ければ先頭)、無い名前は「シート「X」がファイルにありません。…」(`field` は「シート」)。`pd.ExcelFile` は同じバイト列の間だけ id ごとにキャッシュする(シートの切替を速くする)。 @@ -144,16 +153,20 @@ Python が登録し、登録後に `mplgui-ready` イベントを送る。引数 - `dataprep.plan_plot(data, settings)`(`data` は DataFrame または `{ファイル id: DataFrame}`): データ元の解決(`series.source` が空なら `load.files` の先頭)、データ元ごとの `skipRows` の適用と Y 列の自動割り当て、X の数値・日時・文字列の別、描ける点があるか、日時の X の検査(日時と日時でない X の混在、X が日時のときの対数軸(数値の範囲は隠れていて使わない。日時の範囲は §4.1)、Y が日時、はいずれも日本語の `UserError`)、数値に変換できず除外した値の警告(A7)を決める。データ由来の問題は日本語の `UserError`(列が範囲外、除外行数が多すぎる、描ける数値データが無い、など)にする。結果は凍結 dataclass の `PlotPlan` / `SeriesPlan`。 - `codegen.generate_script(settings, source, plan)` は `GeneratedScript`(`text`、`load_lines`、`output_lines`、`steps`)を返す。純粋な関数で、データには触れない。 - スクリプトの構成: ヘッダ(使い方、`import`、日本語フォントの rcParams、欧文フォントの設定(下記)、`FONT_SIZE`)→ `1. データの読み込み`(`DATA_FILE`、`pd.read_csv` / `pd.read_excel`。読込の引数はすべて1行に1つ、コメント付きで明記する(下記))→ `2. 描画に使う行`(`skipRows`)→ `3. 図と軸`(`fig, ax`。単位ごとの書き方は下記)→ `4. 系列` → `5. 軸(ラベル・スケール・範囲・目盛)` → `6. グリッドと凡例` → `7. 余白` → `8. 保存と表示`(形式ごとの rcParams、`fig.savefig(...)`、`plt.show()`)。各セクションの見出しは `# ==== 番号. タイトル ====`。 +- セクション番号(Phase 5b): 見出しの番号は `_Builder.section(title)` が呼んだ順に自動で振る(`_section_count`)。注釈があるときだけ `5. 注釈` が「4. 系列」と「軸」の間に入り、軸以降が 6〜9 に繰り下がる。注釈が無ければ従来と同じ番号・同じ出力。下の「5. 軸」の記述は、注釈が無いときの番号。 - `1. データの読み込み`(Phase 4): 引数は `SourceInfo.read_kwargs()` の順に、既定値も含めてすべて書く(csv: `encoding`(自動判定)、`sep`、`header`、`skiprows`、`thousands`、`decimal`、`comment`、`engine="python"`。xlsx: `sheet_name`、`header`、`skiprows`、`thousands`、`decimal`、`comment`。xlsx では「ファイル内のシート」の一覧もコメントに書く)。ヘッダなしのときは続けて `df.columns = [f"column_{i}" ...]`。日時の列があれば、`# 日時の列を日時に変換する…` に続けて列ごとに `df.isetitem(N, pd.to_datetime(df.iloc[:, N], format="…", errors="coerce")) # 列名 [N]`(前後の空白があれば `.str.strip()`、タイムゾーンの混在は `utc=True`、タイムゾーン付きは `.dt.tz_localize(None)`)。loader も同じ式(`convert_datetime`)を同じ順で適用するので、画面のデータと生成コードの読込結果は一致する。貼り付けたデータ(`SourceInfo.pasted`)のときは、読込部の先頭と「使い方」に「貼り付けたデータを保存して `pasted_data.tsv` として置く」案内を書く(データはスクリプトに埋め込まない)。 - 複数ファイル: `load.files` が1件以下なら `DATA_FILE` / `df`。2件以上なら、系列が使うファイルだけを `DATA_FILE_N` / `dfN`(N = `load.files` の位置 + 1 = 画面の「データN」。使わないファイルがあっても番号は詰めない)で、「データN: ファイル名」の見出しコメント付きで読む。`2. 描画に使う行`(`skipRows`)も `dfN` ごと。系列のコメントと変数は `p.data_var` を使う。 - 軸(Phase 4): X が日時のとき(line / scatter)、`axes.x.dateFormat` が空なら `mdates.AutoDateLocator()` と `mdates.ConciseDateFormatter(date_locator)`、指定があれば `mdates.DateFormatter()`。`import matplotlib.dates as mdates` は日時軸のときだけ書く。棒グラフで X が日時のときは `.dt.strftime(<書式>)` でカテゴリの文字列にして並べる(書式は `dateFormat`、空なら全部 0 時 `%Y-%m-%d` / 秒が全部 0 `%Y-%m-%d %H:%M` / それ以外 `%Y-%m-%d %H:%M:%S`)。X が日時でない文字列の列のときは、Phase 2 の `ax.set_xscale("linear")` を入れず、目盛に X の値(カテゴリ)を出す。描く系列の X のカテゴリ(重複を除く)が 25 個を超えるときだけ `ticker.MaxNLocator(nbins=25, integer=True)` で間引く(`import matplotlib.ticker as ticker` もそのときだけ)。 -- 目盛・反転・枠線・日時の範囲(Phase 5a。「5. 軸」節): 軸ごとの関数 `_axis_tick_lines(blk, settings, plan)`。`blk` は Axes の変数名(`ax` / `ax2`)・軸の向き・`AxisPlan` を持つ `_AxisBlock` で、`dataprep` の `PlotPlan.axes`(実際に効く設定だけ)を文字列にするだけ。行の順は、軸ごとに スケール → 範囲 → 主目盛・書式 → 副目盛 → 反転(スケールを変えると目盛の設定が戻るため)。 +- 目盛・反転・枠線・日時の範囲(Phase 5a。「軸」節。注釈があるときは 6. 軸): 軸ごとの関数 `_axis_tick_lines(blk, settings, plan)`。`blk` は Axes の変数名(`ax` / `ax2`)・軸の向き・`AxisPlan` を持つ `_AxisBlock` で、`dataprep` の `PlotPlan.axes`(実際に効く設定だけ)を文字列にするだけ。行の順は、軸ごとに スケール → 範囲 → 主目盛・書式 → 副目盛 → 反転(スケールを変えると目盛の設定が戻るため)。 - 範囲: X が日時の列なら `ax.set_xlim(left=pd.Timestamp("2026-01-01 00:00:00"), right=...)`(settings が正規化した文字列を `literal()` で書く。数値の `xMin` / `xMax` は使わない)。 - 主目盛: 数値の軸は `ticker.MultipleLocator(間隔)`(対数軸では使わない)。日時の X は `date_locator = mdates.YearLocator(base=n)` / `MonthLocator` / `DayLocator` / `HourLocator` / `MinuteLocator` / `SecondLocator(interval=n)`(単位は `majorStepUnit`)で、表示は `dateFormat` の `DateFormatter`、空なら `ConciseDateFormatter(date_locator)`。文字列の X は `MultipleLocator(n)`(n 個おきにラベル)、複数系列の棒は `tick_step = n`(位置の目盛を `[::tick_step]` で間引く。指定が無ければ従来の 25 個超での間引き)。目盛のラベルの書式は `FormatStrFormatter("%.2f")`(`fixed`)/ `"%.1e"`(`sci`)/ `ScalarFormatter(useMathText=True)` + `set_powerlimits((0, 0))`(`pow10`。対数軸は `LogFormatterSciNotation`。自動以外のとき副目盛の数字は消す)。日時・文字列の軸には書式を使わない。 - 副目盛: すべての軸が `auto` なら従来の書き方(`ax.minorticks_on()` など)のまま。どれかの軸が `auto` 以外のときだけ、軸ごとに書く(`ax.xaxis.minorticks_on()` / `minorticks_off()` / `set_minor_locator(ticker.AutoMinorLocator(n))`。軸ごとの指定を `ax.minorticks_on()` が上書きしてしまうため)。`auto` の軸は従来どおり(副目盛線を表示するときだけ出す。対数軸は出さない)。`on` / `off` は副目盛線の設定にかかわらず従う。 - 反転: `ax.invert_xaxis()` など(範囲を指定していても使える)。枠線: `ax.spines["top"].set_visible(False)`(第2Y軸があるときは `ax2` の上も)。右は第2Y軸が無いときだけ。 - 目盛の本数: `dataprep` が、データの範囲(指定した範囲・エラーバーの端・棒グラフの 0 を含む、余白 5%)と間隔から主目盛の本数を見積もり、`MAX_MAJOR_TICKS`(100)を超えたら日本語の `UserError`(`field` は「X軸の主目盛の間隔」など)。文字列の X はカテゴリの数、日時は期間を単位の長さ(月 30.44 日、年 365.25 日)で割る。ticker を使うときだけ `import matplotlib.ticker as ticker`。手順(`Step`)に「X軸の目盛」などを足してある。 - エラーバー(Phase 5a, G1): line / scatter は、系列本体の直前に `draw_error_bars(ax, x[ok], y[ok], 下端, 上端, direction="y"|"x", color=, linewidth=, capsize=[, zorder=1])` を呼ぶ。関数は、エラーバーを使うときだけスクリプトの冒頭部(`FONT_SIZE` の行の後)に `ERROR_BAR_FUNCTION` の定義を書く(pandas・matplotlib・numpy だけ)。`ax.errorbar` を使わない理由: 点ごとに別の線を作るので、ブラウザで 10,000 行 × 5 系列が約 +1 秒。`draw_error_bars` は、各点の線を NaN で区切った1本の線にまとめ、両端の短い線はその線の端点の記号(`marker="_"` / `"|"`、`markersize=2 * capsize`)で描く(方向ごとに Line2D が1本。見た目は `ax.errorbar` と同じ)。凡例の位置「best」(既定)は全 Line2D の頂点を調べるので、Line2D と頂点を増やさないこと(端の線を別の Line2D にしていたときは、10,000 行 × 5 系列の設定変更が 976 ms、1本にまとめて 795 ms。docs/PERFORMANCE.md「Phase 5a 後」)。ラベルは `_errorbar`(凡例に出ない。`figure_summary` の `errorbars` はこのラベルの線を数える)。scatter は点が上に来るよう `zorder=1`。棒グラフは `ax.bar(..., yerr=..., capsize=..., ecolor="black", error_kw=...)`(複数系列は `bar_data` に誤差の列を足す。X 方向は使わない)。第2Y軸の系列は `ax2` に描く。誤差は `pd.to_numeric(df.iloc[:, N], errors="coerce")`、負の値は `.where(>= 0)` で NaN にし、NaN の点(と `ok` が偽の行)は描かない。`dataprep` が `ErrorPlan`(方式・列番号・固定値・コメント用の列の表示)を作り、数値にできない値と負の値は系列ごとに警告にする(§7)。X が日時・文字列の系列の X 方向は日本語の `UserError`。固定値・列が未入力は settings の `UserError`。手順に「系列Nのエラーバー」を足してある。 +- 系列のスタイル・塗りつぶし帯(Phase 5b, G3): 系列ごとの描く順は 帯(`_emit_band`)→ エラーバー → 系列本体 → 近似曲線(`_emit_fits`)。点の形は、line が `marker=<形>, markersize=<面積> ** 0.5`(`dataprep._marker_plan` の結果。`SeriesPlan.marker` が空なら書かない)、scatter が `marker=<形>`(`auto` は書かない)。不透明度は 1 以外のときだけ `alpha=`(`_alpha_arg`。棒グラフも同じ)。帯は `fill_lower` / `fill_upper`(`pd.to_numeric(df.iloc[:, N], errors="coerce")`)を作り、`ax.fill_between(x[ok], fill_lower[ok], fill_upper[ok], color=系列の色, alpha=, linewidth=0, label="_fill")`(凡例に出ない。第2Y軸の系列は `ax2`)。下端か上端が欠けた点では帯が切れる。数値にできない値は、描く行だけで数えて系列ごとに警告にする(§7)。列が範囲外は日本語の `UserError`(`field` は「系列Nの塗りつぶし帯」)。帯の値は Y の範囲の見積もり(`_Extents`)にも入れる。手順に「系列Nの塗りつぶし帯」を足してある。 +- 近似曲線(Phase 5b, G5): 系列本体の直後に、その系列の `x[ok]` / `y[ok]` で書く。`fit = np.polynomial.Polynomial.fit(x[ok], y[ok], 次数).convert()`(元の X の値での係数。低い次数から `fit.coef`。numpy だけ。`.convert()` を付けるのは、`Polynomial.fit` が X を内部で [-1, 1] に写した係数を返すため)、`r2 = 1 - np.sum((y[ok] - fit(x[ok])) ** 2) / np.sum((y[ok] - y[ok].mean()) ** 2)`、`x_fit = np.linspace(x[ok].min(), x[ok].max(), 200)`、`ax.plot(x_fit, fit(x_fit), color=, linewidth=(系列の線幅), linestyle=, label=...)`。対数軸でも近似は元の値で行う(曲線は曲がって見える)。ラベルは、`show` が `legend` なら `"<名前>の近似: " + poly_text(fit.coef) + f"($R^2$ = {r2:.4f})"`(`<名前>` は系列の凡例名。`_` で始まる自動名のときは「系列N」)、それ以外は `"_fit"`(凡例に出ない)。`show` が `text` なら続けて `ax.text(0.03, y, <同じ文字>, transform=ax.transAxes, va="top", color=, fontsize=FONT_SIZE)`(左上から `y = round(0.97 - 0.07 * 順番, 2)` で下へ並べる。順番は `text` の近似曲線の中の順)。`poly_text(coef)`(`POLY_TEXT_FUNCTION`)は、式の文字(係数は有効数字4桁、`x$^{2}$` のように mathtext で次数を書く)を作る関数で、line / scatter で `show` が `legend` か `text` の近似曲線があるときだけ、冒頭部(`FONT_SIZE` の行の後。`draw_error_bars` があればその後)に定義を書く。第2Y軸の系列の近似曲線は `ax2` に描く。凡例を出すかの判定(`_emit_grid_and_legend`)は、系列のラベルのほかに、注釈の凡例名と `legend` の近似曲線も数える。手順に「近似曲線N」を足してある。 +- 注釈(Phase 5b, G4): 「注釈」節(`_emit_annotations`。系列の後、軸の前)に、1つにつき1行(行末に `# 注釈N: 種類`)。`ax.axhline(y, color=, linewidth=, linestyle=[, alpha=][, label=])`、`axvline`、`axhspan(下, 上, color=, alpha=(既定 0.2), linewidth=0[, label=])`、`axvspan`、`ax.text(x, y, 文字, color=, fontsize=(図と同じなら FONT_SIZE)[, alpha=])`(図の中の割合は `transform=ax.transAxes` を足す)。日時の X は `pd.Timestamp("...")`。Y を使う注釈は、`axis` が `y2` で第2Y軸を使うときだけ `ax2`。凡例名は `label=` で書き、空なら書かない(凡例に出ない)。手順に「注釈N」を足してある。 - 既定の設定(目盛・枠線・エラーバーを使わない)の生成コードは、Phase 4 と1文字も変わらない。`tests/unit/golden/*.py.txt`(Phase 4 のコードで生成した出力)と `test_codegen_compat.py` が強制する。新しい行は、その機能を使ったときだけ書くこと。 - 欧文フォント(`plot.latinFont` が `arimo` / `tinos` のときだけ。`default` ではヘッダは Phase 2 と同じ): ヘッダに `from matplotlib import font_manager` を足し、`installed = {font.name for font in font_manager.fontManager.ttflist}`、`latin = [name for name in [候補…] if name in installed][:1]`、`plt.rcParams["font.family"] = latin + ["sans-serif"]` を書く。候補は `fonts.LATIN_FONTS` の並び(Arimo: `Arimo`、`Arial`、`Liberation Sans`。Tinos: `Tinos`、`Times New Roman`、`Liberation Serif`)。入っているフォントだけを選ぶのは、無い名前を `font.family` に並べると、matplotlib が描画のたびに `findfont` の警告を出すため(ローカルで実行しても警告を出さず、どれも無ければ日本語フォントで書く)。日本語の文字は、リストの後ろの `sans-serif`(`font.sans-serif` の日本語フォント)に、matplotlib の文字単位のフォールバックで回る。Tinos(`mathtext_fontset` = `stix`)のときは `plt.rcParams["mathtext.fontset"] = "stix"` も書く(数式も Times 系の字形にする。STIX は matplotlib 同梱)。 - `3. 図と軸`: `figsize` はインチ。`unit` が `in` なら `figsize=(幅, 高さ)`。`cm` / `mm` なら `CM_PER_INCH = 2.54`(`MM_PER_INCH = 25.4`)を定義し、`figsize=(幅 / CM_PER_INCH, 高さ / CM_PER_INCH)` と割る(コメントに単位と値を書く)。`1 / 2.54` を掛けると、20.32 cm が 7.999… inch になり、Agg の画素数(切り捨て)が 1 画素欠けるため、割り算にする(Python 側の `FigureSettings.width_in` も同じ割り算)。 @@ -163,7 +176,7 @@ Python が登録し、登録後に `mplgui-ready` イベントを送る。引数 - 手順(`Step`): 失敗しうる行の範囲と日本語メッセージ(`field` 付きのものもある)の対応表。系列の描画(`GENERIC_ERROR_MESSAGE`)、軸のスケール・範囲(X / Y / 第2Y)、`tight_layout`、`subplots_adjust`(余白)を登録している。 - **安全性(必須)**: 列名・タイトル・ラベル・色・ファイル名・文字コード・シート名・コメント記号・日時の書式・貼り付けたデータのファイル名などは信頼できない入力で、実行されるコードに入る。値は必ず `literal()`(str / int / 有限の float / bool / None だけを `repr` で出す。他の型は例外)を通して書き出し、コメントに入れる文字列は必ず `comment_text()`(改行・制御文字を空白にする)を通す。f 文字列などで、これ以外の方法で信頼できない文字列をコードに埋め込まないこと。`tests/unit/test_codegen.py`(と `test_load_options.py` / `test_datetime.py` / `test_multi_source.py` / `test_paste_tsv.py`)の注入テストが、シート名・ファイル名・コメント記号・日時の書式・列名で検査する。 - GUI の設定を、ユーザーが編集したコードの結果に上書き適用しない(A8)。編集モードのコードは、設定を使わずそのまま実行する。 -- 機能追加(Phase 5〜)の手順(5a で足した軸ごと・系列ごとの機能の足し方を含む): 描画の種類は `SERIES_EMITTERS`(プロット種別 → 系列の出力関数)に追加する。出力関数は `_Builder` に行を足し、失敗しうる行は `with b.step(メッセージ, field)` で包む。軸・グリッド・余白などは対応する `_emit_*` 関数に足す。データを見ないと決められないこと(列の割り当て、変換の要否、警告、データ由来のエラー)は `dataprep` の `PlotPlan` / `SeriesPlan` に項目を足して渡す(データ元ごとに違うことは `SeriesPlan.data_id` / `data_var` と `PlotPlan.sources` に持つ。読込の仕方に関わる引数は `SourceInfo.read_kwargs()` に足し、codegen の `_READ_COMMENTS` にコメントを足す)。設定項目を足すときは JS の `defaults.js` と `settings.py` の両方に足す。生成するコードは pandas / matplotlib / numpy だけを使う(ローカルの Python でそのまま動かすため)。新しい行を足したら、単体テストで「全体を実行した図」と「自動描画用の図」が一致することも確かめる。保存形式ごとの rcParams は `formats.savefig_rc` に足す(runner と codegen が同じ表を使う)。欧文フォントを足すときは `fonts.LATIN_FONTS`・`FONT_FILENAMES`、JS の `font-cache.js` の `FONT_URLS`・`bridge.js` の `LATIN_NAMES`、`settings.LATIN_FONTS`、`index.html` の選択肢を揃える。 軸ごとの機能は、`settings._parse_axis` に項目(隠れる条件では検証しない)、`dataprep._plan_axis` / `AxisPlan` に「その軸の種類で効く値」(使えない組み合わせは `UserError`)、`codegen` の `_axis_tick_lines` に `_AxisBlock`(Axes の変数名を引数で受ける。`ax` 固定の書き方を増やさない)を足す。系列ごとの付属物(エラーバーなど)は、`settings` の系列の項目 → `dataprep` の `SeriesPlan` の項目(列は系列のデータ元の `df.iloc[:, N]` から解決し、データ元を替えたら JS が列を空に戻す)→ `SERIES_EMITTERS` の各関数から呼ぶ小さな関数、の順に足し、描く順は「付属物 → 系列本体」にする。画面で隠す条件は、JS(`syncVisibility` / `axisTicks.js`)と Python(settings / dataprep)で同じ規則にし、隠した設定は図に使わない。軸の種類の規則を変えたら `series.js` の `xAxisKind` も揃える。既定の設定の出力が変わらないことを、ゴールデンテストで確かめる。 +- 機能追加(Phase 5〜)の手順(5a で足した軸ごと・系列ごとの機能の足し方を含む): 描画の種類は `SERIES_EMITTERS`(プロット種別 → 系列の出力関数)に追加する。出力関数は `_Builder` に行を足し、失敗しうる行は `with b.step(メッセージ, field)` で包む。軸・グリッド・余白などは対応する `_emit_*` 関数に足す。データを見ないと決められないこと(列の割り当て、変換の要否、警告、データ由来のエラー)は `dataprep` の `PlotPlan` / `SeriesPlan` に項目を足して渡す(データ元ごとに違うことは `SeriesPlan.data_id` / `data_var` と `PlotPlan.sources` に持つ。読込の仕方に関わる引数は `SourceInfo.read_kwargs()` に足し、codegen の `_READ_COMMENTS` にコメントを足す)。設定項目を足すときは JS の `defaults.js` と `settings.py` の両方に足す。生成するコードは pandas / matplotlib / numpy だけを使う(ローカルの Python でそのまま動かすため)。新しい行を足したら、単体テストで「全体を実行した図」と「自動描画用の図」が一致することも確かめる。保存形式ごとの rcParams は `formats.savefig_rc` に足す(runner と codegen が同じ表を使う)。欧文フォントを足すときは `fonts.LATIN_FONTS`・`FONT_FILENAMES`、JS の `font-cache.js` の `FONT_URLS`・`bridge.js` の `LATIN_NAMES`、`settings.LATIN_FONTS`、`index.html` の選択肢を揃える。 軸ごとの機能は、`settings._parse_axis` に項目(隠れる条件では検証しない)、`dataprep._plan_axis` / `AxisPlan` に「その軸の種類で効く値」(使えない組み合わせは `UserError`)、`codegen` の `_axis_tick_lines` に `_AxisBlock`(Axes の変数名を引数で受ける。`ax` 固定の書き方を増やさない)を足す。系列ごとの付属物(エラーバーなど)は、`settings` の系列の項目 → `dataprep` の `SeriesPlan` の項目(列は系列のデータ元の `df.iloc[:, N]` から解決し、データ元を替えたら JS が列を空に戻す)→ `SERIES_EMITTERS` の各関数から呼ぶ小さな関数、の順に足し、描く順は「付属物 → 系列本体」にする。画面で隠す条件は、JS(`syncVisibility` / `axisTicks.js`)と Python(settings / dataprep)で同じ規則にし、隠した設定は図に使わない。軸の種類の規則を変えたら `series.js` の `xAxisKind` も揃える。既定の設定の出力が変わらないことを、ゴールデンテストで確かめる。 注釈・近似曲線のような設定のトップレベルの一覧(5b)は、`settings` に要素の dataclass と `_parse_*`(上限、id の重複の振り直し、隠れる条件では検証しない)、`dataprep` に解釈済みの値を持つ `*Plan`(位置の解釈・データ由来の検査はここ。範囲に効くものは `_Extents` に足す)と `PlotPlan` の項目、`codegen` に `_emit_*`(新しい節は `b.section(タイトル)` を呼ぶだけで番号は自動。節が増えても、その機能を使わないときの出力は変えない)と `Step` を足す。JS は `defaults.js` に要素の既定値、`state.js` に追加・更新・削除と通知の `kind`(一覧と項目を分ける。id は連番で再利用しない)、`js/ui/` にカード(`addVisibilityHook` で表示の同期を登録)、`main.js` の購読に一覧の再描画を足す。画面に出す要素の id は `<種類>--<項目>`。`runner._style_summary` に数えるキーを足して、E2E の一致確認(`test_codegen_consistency.py` の `EXACT_KEYS`)に加える。 - 生成スクリプトの保存ファイル名(`savefig` の引数)は `formats.build_filename` で決める。保存形式・解像度・形式ごとの rcParams は `formats.savefig_kwargs`(解像度は `save.dpi`)/ `formats.savefig_rc` で、GUI の「保存」と同じにする。 ### runner(スクリプトの実行) @@ -178,7 +191,7 @@ Python が登録し、登録後に `mplgui-ready` イベントを送る。引数 ## 5. 描画パイプライン - 描画は設定変更の 250 ms 後(デバウンス)。読込は、ファイル選択・ヘッダ変更・シート変更・桁区切り・小数点・日時の自動認識の変更で 0 ms、入力欄(区切り文字・ヘッダより前に読み飛ばす行数・コメント記号)の変更で 450 ms 後(`bridge.js` の `LOAD_DELAY_MS` / `SLOW_LOAD_PATHS`)。読込設定(`load.*`)の変更は全ファイルを読み直す。ファイル一覧のシート変更は、そのファイルだけを読み直す(`load.files` の変更に `fileId` が付く)。保存設定(`save.*`)の変更では再描画しない(画像の画素は保存設定に依存しないため)。`skipRows` の変更は Python を呼ばず、データ確認表のグレー表示だけ即時に更新する。 -- Phase 5a の新しい項目(目盛・反転・日時の範囲・枠線・エラーバー)は `load.*` でも `save.*` でもないので、経路は増えない。すべて通常の変更として 250 ms 後に再描画し、コードタブ(GUI 同期)は描画に成功したら新しいコードになる。失敗(目盛が多すぎる、エラーバーの列が未選択など)は「最新でない」印(`data-stale`)になり、直すと消える。編集モード中は図もコードも変えない(A8)。 +- Phase 5a の新しい項目(目盛・反転・日時の範囲・枠線・エラーバー)は `load.*` でも `save.*` でもないので、経路は増えない。すべて通常の変更として 250 ms 後に再描画し、コードタブ(GUI 同期)は描画に成功したら新しいコードになる。失敗(目盛が多すぎる、エラーバーの列が未選択など)は「最新でない」印(`data-stale`)になり、直すと消える。編集モード中は図もコードも変えない(A8)。 Phase 5b の新しい項目(点の形・不透明度・帯・並べ替え・複製・注釈・近似曲線)も同じ。注釈と近似曲線の変更の通知(`annotation-list` / `annotation-field` / `fit-list` / `fit-field`。`path` ではない種別)は、`bridge.js` の `routeChange` で系列の変更と同じ「通常の変更」になる(250 ms 後に再描画。編集モードでは何もしない)。画面の注意は `addNote` で次の描画結果の警告に1度だけ添える: 系列を削除して近似曲線も消えたとき(「系列Nを削除したため、その系列の近似曲線M本も削除しました。」)、データ元を替えたとき(「系列N: データ元を替えたため、塗りつぶし帯の列を空に戻しました(帯は描きません)。」)、読み込み直しで帯の列が無くなったとき(「系列N: 塗りつぶし帯の列が無くなったため、帯の列を空に戻しました。」)。 - 起動中の `#progress`(`aria-live="polite"`)は段階表示: 「Python 実行環境を読み込み中…」→「ライブラリを読み込み中…(pandas ✓, matplotlib …)」→「ライブラリを初期化中…」→ 準備完了で消える(フォント取得の表示が続く場合あり)。`` の `data-startup-stage`(`runtime` / `packages` / `init` / `ready`)に現在の段階が入る。新しい id は無い。読込失敗の案内(`data-load-failed`)は上書きしない。 - 保存設定(`save.*`: ファイル名・形式・背景透過・DPI・SVG の文字)の変更は、GUI 同期のときだけ、250 ms 後に `script` API でコードだけを作り直す(`bridge.js` の `refreshScript`)。画像は描き直さず、コードの世代(`#customPyCode` の `data-generation`)は表示中の画像のまま(`code-state.getGeneratedGeneration()`)。描画が予約中・実行中のときは何もしない(描画が新しいコードを返す。実行中だったら終了後にもう一度確かめる)。コードの更新に失敗したら(保存設定の不正など)エラーを表示し、次に成功したときに直近の描画成功のステータスへ戻す。編集モードでは何もしない。 - 描画要求には世代番号を付ける。Python の描画は同時に最大1つ。実行中に新しい要求が来たら「やり直し」の印だけ付け、終了後に最新の設定で1回だけ描く(合流)。古い世代の結果は画像にもステータスにも反映しない。 @@ -193,7 +206,7 @@ Python が登録し、登録後に `mplgui-ready` イベントを送る。引数 - 「編集」で `edit`、「GUI から再生成」で `sync` に切り替える。切り替えのたびに、予約中・実行中の描画を無効にする(世代を進め、結果は画像にもコードにもステータスにも反映しない)。このため `data-render-generation` は、モード切替の直後に、表示中の画像の世代より先に進んだままになることがある。E2E は `tests/e2e/helpers.py` の専用ヘルパー(`wait_code_generated`、`wait_image_generation_changed`、`run_edited_code`、`wait_run_finished`)で待つこと。 - `sync` の描画は読込済みデータが必要。`edit` は Python が動いていればよい(コードが自分でファイルを読む)。 - 欧文フォント(`plot.latinFont`): 選んだときだけ取得する(既定の `default` では取得しない)。Python の起動前に選んでいたら、起動後に取得する。取得中の描画・保存・コピーは、`waitForFonts` が最大 `FONT_FIRST_RENDER_WAIT_MS`(8 秒)待つ。超えたらその種類は待ちを打ち切り、標準フォントで描き、取得・登録が済んだら(選択中のままなら)現在の設定で1回だけ描き直す(編集モードでは「実行」したことがあるときだけ)。取得は種類ごとにセッション中1回で、失敗しても再試行しない。失敗したら、選択中のあいだ警告「欧文フォント Arimo(または Tinos)を取得できなかったため、標準のフォントで描画しています。」を常時警告に1度だけ出し、標準(`default`)に戻すと消える(取得を再試行しない)。編集モードでも欧文フォントの取得・登録はするが、描画もコードも触らない。取得中は進捗バナーに「欧文フォントを取得中…」。 -- 左パネルは `details.panel-section`(`#sectionLoad` データ読み込み(ファイル・貼り付け・シート・区切り文字・ヘッダ・読み飛ばす行数・桁区切り・小数点・コメント記号・日時の自動認識)、`#sectionSeries` 系列(描画から除外する先頭行数を含む)、`#sectionAxes` 軸・目盛、`#sectionStyle` 体裁、`#sectionSave` 保存)に分かれ、既定はすべて開く。折りたたみの状態は localStorage の `mplgui.panelSections` に持つ(`panelSections.js`)。ステータス(`#status`)は区分の外にあり、閉じていても見える。「注釈・解析」の区分は Phase 5 まで作らない。体裁区分は、プリセット(`#stylePreset`、「適用」`#applyPresetBtn`)、`#colorPalette`、`#latinFont`、`#fontSize`、図サイズ(`#figWidth` / `#figHeight` / `#figUnit`)、凡例位置、グリッド、余白。軸・目盛区分には数式の案内(`#mathtextHelp`。matplotlib 3.10.8 の mathtext ページへのリンク)と、X が日時の列のときだけ出る日時の書式(`#xDateFormatGroup`。line / scatter はどれかの系列の X、bar は `#xColumn` が日時の列のとき)がある。Phase 5a で軸・目盛区分に、各軸の範囲の下の折りたたみ「X軸の目盛」`#xTickGroup` / 「Y軸の目盛」`#yTickGroup` / 「第2Y軸の目盛」`#y2TickGroup`(第2Y軸を使うときだけ表示)を足した。中身は主目盛の間隔(`#xMajorStep` / `#yMajorStep` / `#y2MajorStep`、補足 `*MajorStepHelp`、日時の X では単位 `#xMajorStepUnit`(`#xMajorStepUnitWrap`))、副目盛(`*MinorTicks`、分割数 `*MinorDivisions`)、ラベルの書式(`*TickFormat`、桁数 `*TickDecimals`)、軸の反転(`*Inverted`)。X の数値の範囲の行は `#xRangeGroup`、日時の範囲は `#xDateRangeGroup`(`#xDateMin` / `#xDateMax`、X が日時の列のときだけ表示)。グリッドの下に「上の枠線」`#spineTop`・「右の枠線」`#spineRight`(第2Y軸があるときは無効にして補足 `#spineRightHelp`)。表示と無効の切り替えは `axisTicks.js` の `syncAxisTicks(xKind)`(`xKind` は `series.js` の `xAxisKind()`。X 列・グラフの種類・スケール・第2Y軸・読み込んだ列が変わるたびに呼ぶ)。対数軸では主目盛の間隔を無効にし、副目盛を「表示」にしたときだけ分割数(対数軸と文字列の X では出さない)、書式が小数・指数のときだけ桁数、日時と文字列の X では書式を隠す。系列カードの「エラーバー」は `
`(既定は閉じ、使っている系列は開いて作る)で、入力欄は `series--yerr-mode` / `-yerr-symmetric` / `-yerr-value` / `-yerr-value-minus` / `-yerr-column` / `-yerr-column-minus`(X 方向は `xerr`。棒グラフでは `.err-x-wrap` ごと隠す)と `series--err-capsize`。系列のデータ元を替えると、X・Y に加えて誤差の列も空に戻す(方式はそのまま。列を選び直すよう日本語のエラーで案内する)。保存区分は `#saveDpi`(+ 任意の `#saveDpiCustom`)、SVG のときだけ `#svgTextGroup`(`#svgText`)、PDF のときだけ `#pdfHelp`、`#savePlotBtn`、`#copyPlotBtn`。 +- 左パネルは `details.panel-section`(`#sectionLoad` データ読み込み(ファイル・貼り付け・シート・区切り文字・ヘッダ・読み飛ばす行数・桁区切り・小数点・コメント記号・日時の自動認識)、`#sectionSeries` 系列(描画から除外する先頭行数を含む)、`#sectionAxes` 軸・目盛、`#sectionStyle` 体裁、`#sectionSave` 保存)に分かれ、既定はすべて開く。折りたたみの状態は localStorage の `mplgui.panelSections` に持つ(`panelSections.js`)。ステータス(`#status`)は区分の外にあり、閉じていても見える。「注釈・解析」の区分(`#sectionAnalysis`)は Phase 5b で、軸・目盛と保存の間に作った(既定で開く。順序は `tests/e2e/test_panel_sections.py` が確かめる)。体裁区分は、プリセット(`#stylePreset`、「適用」`#applyPresetBtn`)、`#colorPalette`、`#latinFont`、`#fontSize`、図サイズ(`#figWidth` / `#figHeight` / `#figUnit`)、凡例位置、グリッド、余白。軸・目盛区分には数式の案内(`#mathtextHelp`。matplotlib 3.10.8 の mathtext ページへのリンク)と、X が日時の列のときだけ出る日時の書式(`#xDateFormatGroup`。line / scatter はどれかの系列の X、bar は `#xColumn` が日時の列のとき)がある。Phase 5a で軸・目盛区分に、各軸の範囲の下の折りたたみ「X軸の目盛」`#xTickGroup` / 「Y軸の目盛」`#yTickGroup` / 「第2Y軸の目盛」`#y2TickGroup`(第2Y軸を使うときだけ表示)を足した。中身は主目盛の間隔(`#xMajorStep` / `#yMajorStep` / `#y2MajorStep`、補足 `*MajorStepHelp`、日時の X では単位 `#xMajorStepUnit`(`#xMajorStepUnitWrap`))、副目盛(`*MinorTicks`、分割数 `*MinorDivisions`)、ラベルの書式(`*TickFormat`、桁数 `*TickDecimals`)、軸の反転(`*Inverted`)。X の数値の範囲の行は `#xRangeGroup`、日時の範囲は `#xDateRangeGroup`(`#xDateMin` / `#xDateMax`、X が日時の列のときだけ表示)。グリッドの下に「上の枠線」`#spineTop`・「右の枠線」`#spineRight`(第2Y軸があるときは無効にして補足 `#spineRightHelp`)。表示と無効の切り替えは `axisTicks.js` の `syncAxisTicks(xKind)`(`xKind` は `series.js` の `xAxisKind()`。X 列・グラフの種類・スケール・第2Y軸・読み込んだ列が変わるたびに呼ぶ)。対数軸では主目盛の間隔を無効にし、副目盛を「表示」にしたときだけ分割数(対数軸と文字列の X では出さない)、書式が小数・指数のときだけ桁数、日時と文字列の X では書式を隠す。系列カードの「エラーバー」は `
`(既定は閉じ、使っている系列は開いて作る)で、入力欄は `series--yerr-mode` / `-yerr-symmetric` / `-yerr-value` / `-yerr-value-minus` / `-yerr-column` / `-yerr-column-minus`(X 方向は `xerr`。棒グラフでは `.err-x-wrap` ごと隠す)と `series--err-capsize`。系列のデータ元を替えると、X・Y に加えて誤差の列も空に戻す(方式はそのまま。列を選び直すよう日本語のエラーで案内する)。保存区分は `#saveDpi`(+ 任意の `#saveDpiCustom`)、SVG のときだけ `#svgTextGroup`(`#svgText`)、PDF のときだけ `#pdfHelp`、`#savePlotBtn`、`#copyPlotBtn`。 Phase 5b で系列カードに、点の形 `series--marker`(`.series-marker-wrap`)、不透明度 `series--alpha`、折りたためる「塗りつぶし帯」`series--fill`(`
`。使っている系列は開いて作る。入力欄は `-fill-lower` / `-fill-upper`(列の選択。「(なし)」あり)と `-fill-alpha`)、並べ替えと複製のボタン `series--up` / `-down` / `-duplicate`(先頭の ↑・末尾の ↓・系列が1つのときの削除は無効)を足した。棒グラフでは点の形と帯を隠す(不透明度は残す)。点の形が「なし」の line は点サイズ欄を無効にする。「注釈・解析」区分(`#sectionAnalysis`)は、注釈(`#annotationList`、`#addAnnotationBtn`)と近似曲線(`#fitList`、`#addFitBtn`、棒グラフのときだけ出る `#fitBarNote`)の2つ。注釈カードは `annotation-`、入力欄は `annotation--kind` / `-text` / `-coords` / `-x` / `-y` / `-start` / `-end` / `-axis` / `-alpha` / `-line-style` / `-line-width` / `-font-size` / `-label` / `-remove`、色は `annotation--color-trigger`(色の選択UI)。種類ごとの表示は `text`: 文字・位置の指定・X・Y・文字の大きさ、`hline`: Y・線種・線幅・凡例名、`vline`: X・線種・線幅・凡例名、`hspan` / `vspan`: 開始・終了・凡例名(色と不透明度はどれも出す。Y 軸の選択は、第2Y軸があり Y を使う種類のときだけ)。X の欄の例と補足は軸の種類で変える(数値 / 日時 / 文字列は何番目か。位置の指定が「図の中の割合」の `text` は 0〜1)。近似曲線カードは `fit-`、入力欄は `fit--series`(選択肢は「系列N(名前)」)/ `-model` / `-degree`(多項式のときだけ)/ `-show` / `-color`(`""` = 系列の色、`custom` = 色を選ぶ)/ `-line-style` / `-remove`、色の選択UIの `fit--color-picker-trigger`(「色を選ぶ」のときだけ)。追加ボタンは、注釈が 50 個、近似曲線が 20 本で無効になる(近似曲線は棒グラフでは一覧ごと隠す)。カードの表示の同期は `syncAnnotations` / `syncFits`(`series.js` の `syncVisibility` の最後に呼ばれる)。 - 図サイズの単位を替えると、入力欄の数値を換算し(`convertLength`。空欄・不正な入力はそのまま)、図の大きさは変えない。ラベル(`図幅(inch)` など)と step は単位に合わせる。プリセットの「適用」は値を書き込むだけで、描画は通常の変更どおり。パレットを替えると、色の選択肢と各系列の色を描き直す。 - 「クリップボードにコピー」(`clipboard.js`): 保存 DPI の PNG を `copyImage` で作り、`ClipboardItem` に `Promise` として渡して `navigator.clipboard.write` する(Safari がクリックの中での呼び出しを要求するため、クリックの処理では何も `await` せずに `write` を呼び、画像は渡した Promise の中で作る)。対応は `window.isSecureContext`(https または localhost)、`navigator.clipboard.write`、`ClipboardItem`(`ClipboardItem.supports("image/png")` があれば true)。編集モードでは編集中のコードの図をコピーする。 - E2E が使う状態は `` の data 属性: `data-app-state`(`starting` / `ready` / `failed`)、`data-data-state`(`none` / `loading` / `ready` / `error`)、`data-render-state`(`idle` / `pending` / `rendering`)、`data-render-generation`、`data-font-state`(日本語フォント。`idle` / `loading` / `ready` / `failed`)、`data-latin-font-state`(選択中の欧文フォント。`idle`(標準を選択中)/ `loading` / `ready` / `failed`)、`data-copy-state`(`idle` / `copying` / `done` / `failed` / `unsupported`)、`data-load-count`(読み込めたデータ元がある読込のまとまりの完了ごとに増える。ファイルを外しただけ・全ファイルの失敗では増えない)。複数ファイルのとき、`data-data-state` は読込中が1つでもあれば `loading`、読込中がなく失敗が1つでもあれば `error`、すべて成功なら `ready`、ファイルが無ければ `none`。表示中の画像は `#plotArea img` の `data-generation` と `data-summary`(`figure_summary` の JSON)を持つ。ステータスは `#status` の `data-kind`。Pythonコードタブ用に、`` の `data-code-mode`(`sync` / `edit`)、`#customPyCode`(textarea)の `data-generation`(表示中のコードを生成した世代。GUI 同期のとき、同じ世代の画像と対応する)、`#codeOutput` の `data-kind`(`ok` / `error`)、`#codeSyncStatus` の `data-state`(`sync` / `edit`)、`#customPyCode` の `data-stale`(最新でないときだけ `true`)、`#codeStaleNote` がある。Phase 4 の画面の id: データ読み込み区分の `#fileInput` / `#addFileBtn` / `#addFileInput` / `#fileList` / `#pasteArea` / `#savePastedBtn` / `#sheetGroup` / `#sheetSelect` / `#skipLines`(+ `#skipLinesHelp`)/ `#thousands` / `#decimal` / `#commentChar` / `#parseDates`、系列区分の `#skipRowsHelp` / 系列カードの `series--source`、軸・目盛区分の `#xDateFormatGroup` / `#xDateFormat` / `#xDateFormatCustom`、データ確認の `#dataPreamble` / `#previewSource`(+ `#previewSourceGroup`)、ドロップの `#dropOverlay` / `#dropLoad` / `#dropReplace` / `#dropAdd`。 @@ -215,6 +228,8 @@ Python が登録し、登録後に `mplgui-ready` イベントを送る。引数 - 文字コード(`loader.detect_encoding`): BOM 付きなら utf-8-sig → UTF-8 → CP932 と EUC-JP。両方でデコードできるときは、半角カナ・私用領域・制御文字などの「文字化けらしい文字」が少ないほうを採用し、同数なら CP932。どれでも読めなければ日本語のエラーにする。判定結果は `#encodingLabel` に表示する。 - 数値に変換できず除外した値は、系列ごとに警告にする(`dataprep.dropped_warning`。`dataprep.plan_plot` が集める)。 - エラーバーの誤差の列に、数値にできない値があれば、系列ごとに警告にする(「系列N: Y誤差の列「name」[i] に数値にできない値がN件あったため、その点のエラーバーは描きません(例: …)」。桁区切り・小数点のヒントも付く。空欄は警告しない)。負の値も、系列ごとに件数と例の警告にして、その点のエラーバーは描かない。件数と例は、実際に描く行だけで数える(`dataprep._error_values`)。 +- 塗りつぶし帯の列(下端・上端)に数値にできない値があれば、系列ごとに警告にする(「系列N: 塗りつぶし帯(下端)の列「name」[i] に数値にできない値がN件あったため、その点の帯は描きません(例: …)」。桁区切り・小数点のヒントも付く。空欄は警告しない)。件数と例は、実際に描く行だけで数える(`dataprep._band_values`)。 +- 注釈・近似曲線のエラーは警告ではなく `UserError`(描画は止まり、コードタブには「最新でない」印が付く)。注釈: 位置の未入力・数でない・日時でない・対数軸で 0 以下・`text` の文字が空(「注釈NのX」「注釈Nの開始」など。§3)。近似曲線: 日時・文字列の X、X の異なる値の不足、Y が一定、描ける点が無い系列(「近似曲線N: …」。§3)。 - 主目盛の間隔が小さすぎて目盛が 100 本(`dataprep.MAX_MAJOR_TICKS`)を超えるときは、警告ではなくエラー(「X軸の主目盛の間隔が小さすぎます(目盛が約N本になります。100本まで)。…」。`field` は「X軸の主目盛の間隔」など)。コードタブには「最新でない」印が付く。 - 数値に変換できず除外した値の例が「1,234」のような桁区切りの数で `thousands` がカンマでないとき、「1,5」のような小数点カンマで `decimal` がカンマでないときは、警告の文に「(桁区切りのカンマなら、「データ読み込み」の「桁区切り」をカンマにしてください)」「(小数点がカンマなら、「小数点」をカンマにしてください)」を添える(`dataprep.load_hint`。両方に当てはまる `1,234` は桁区切りのヒントだけ)。 - 日時の列の認識(`loader.detect_datetime_columns`。`load.parseDates` が true のときだけ。Excel の日付セル(もともと datetime の列)は設定にかかわらず日時): 読込後に数値でない文字列の列のうち、空欄以外の半数以上が数値に読める列は除く。書式は年が先頭の固定の候補だけ(日付 `%Y-%m-%d` / `%Y/%m/%d` / `%Y年%m月%d日`、時刻は無し / ` %H:%M` / ` %H:%M:%S` / ` %H:%M:%S.%f`、`%Y-%m-%d` には ISO の `T` 区切りも、時刻のあるものには末尾 `%z`(`Z` と `+09:00`)も)。前後の空白を除いた先頭 100 個の空欄以外の値の 90% 以上が読める書式のうち最も多く読めるものを選び、列全体でも 90% 以上が読めれば日時の列にする。月日の順が曖昧な `01/02/2024`、時刻だけ、年月だけは認識しない。読めない値は NaT にして、列ごとに警告(「列「name」[i]: 日時として読めない値がN件あったため、欠損として扱います(例: …)」。例は最大3件)。`%z` 付きは、全行が同じオフセットなら書かれた時刻のまま、混在していれば UTC にそろえて警告する。日時の列は `columns[].kind` が `datetime` になり、データ確認の列見出しに「日時」の印が付く。日時の X で描くときの検査は §4.1。 @@ -275,6 +290,13 @@ uv run pytest tests/e2e # E2E(Chromium とローカルの静的サー - `test_codegen_compat.py`(`golden/`・`golden_cases.py`): 既定の設定の生成コードが Phase 4 と1文字も変わらないこと。`test_js_modules.py`: `version` が 4、新しい系列の `errorBars`。 - Phase 5a で加えた E2E: `test_ticks.py`(主目盛・副目盛・書式・反転・枠線と第2Y軸、対数軸で間隔が無効、日時の単位と範囲と数値の範囲の欄の出し分け、不正な日時の範囲は X が日時のときだけエラー、文字列の X と複数系列の棒の間隔、目盛が多すぎるエラーと復帰(コードに「最新でない」印)、隠れた桁数・分割数が描画を止めない)、`test_errorbars.py`(カードの既定と欄の出し分け、列・非対称・固定値、scatter と X 方向、棒グラフ(X 方向を隠す・複数系列)、日時の X、2ファイルでデータ元に追従、警告、列未選択のエラーと復帰、カードの開閉が系列の追加で保たれる、凡例が変わらない)。`test_codegen_consistency.py` に、エラーバー(line・scatter・棒・複数系列の棒・2ファイル)と目盛(`ticks_fixed_inverted` / `ticks_pow10` / `datetime_day_step_range` / `text_x_step`)の一致確認を足した。`test_datetime.py` は日時の X の範囲指定の新しい動きに合わせた。 - `helpers.py` の Phase 5a 用ヘルパー: `open_tick_group`、`set_axis_option`、`wait_error_status`、`code_value`、`is_hidden_by_id`、`eb_id`、`set_errorbars`、`error_bar_count`、`series_errorbars`。 +- Phase 5b で加えた単体テスト: + - `test_series_style.py`: 点の形(line の `auto` は従来どおり、形を選んだときの点サイズ、`none` は点サイズを使わない、scatter の形と `none` のエラー)、不透明度(既定はコードに書かない、棒グラフ、検証、`figure_summary` の `alphas`)、帯(既定は無い、列の解決、系列本体より先に描く、scatter と第2Y軸、欠損で帯が切れる警告、警告は描く行だけで数える、桁区切りのヒント、列が範囲外、片方が空はエラー、日時・文字列の X、範囲の見積もりへの反映、棒グラフでは使わない、凡例名の注入)。補助は `style_helpers.py`。 + - `test_annotations.py`: 既定、欠けたキーの補完と数値の文字列化、上限 50、使わない項目を検証しないこと、使う項目の検証、第2Y軸があるときだけ `axis` を検証、位置のエラー(日時の X、対数軸、日付を数値軸に入れる)、軸の種類ごとの値の解釈、隠れた第2Y軸では `ax` に戻ること、目盛の本数の見積もりに含まれること、注釈が無いとき「注釈」節が無いこと、番号の繰り下がり、各種類の生成コードを実行した artist、日時の X、文字列の X の位置(カテゴリ番号)、棒グラフ、第2Y軸、凡例名だけで凡例が出ること、既存の系列の要約が変わらないこと、コード注入、手順の登録。 + - `test_fits.py`: `poly_text` の書式、既定と検証、上限 20、`linear` で次数を検証しないこと、棒グラフでは使わないこと、numpy との一致(1次・多項式・X が大きいときの安定性)、描いた行だけで近似すること、scatter、`legend` / `text` / `none` の出し分けと `poly_text` の定義の有無、色と線種、第2Y軸、系列の直後に描くこと、X が既定(行番号)のとき、対数軸、データのエラー(日時・文字列・異なる X の不足・欠損を除いた点の不足・Y が一定・点が無い系列)、系列名・列名の注入、生成コードが numpy だけを使うこと。 + - `test_settings.py`: 5b の既定値、v3 の設定(5b のキーなし)が既定値で読めること、系列の点の形・不透明度・帯の検証と `field`(系列番号入り)、帯が無いときに不透明度を検証しないこと、棒グラフで点の形と帯を隠すこと、注釈・近似曲線の要素の補完とリスト型の検査、注釈 id の重複の振り直し。`test_defaults_parity.py` は `DEFAULT_ANNOTATION` / `DEFAULT_FIT` も Python と比べる。`test_runner.py`: `figure_summary` の 5b のキーの既定値。`test_js_modules.py`: 系列の移動と複製、注釈・近似曲線の追加・削除と id の非再利用、系列の削除で近似曲線が消えること。 +- Phase 5b で加えた E2E: `test_series_style.py`(点の形・不透明度・帯、日時の X の帯、データ元を替えると帯の列が戻って警告が出ること、並べ替えと複製)、`test_annotations.py`(区分の表示と数値の X の全種類、日時・文字列の X と第2Y軸、編集モードで注釈・近似曲線の変更が図もコードも変えないこと、狭い画面で横スクロールが出ないこと)、`test_fits.py`(1次式の凡例・多項式の図の中・系列の選択、日時の X のエラーと復帰)、`test_panel_sections.py`(区分の順序に「注釈・解析」)。`test_codegen_consistency.py` に、8 つの一致確認(`style_line_band` / `band_datetime_scatter` / `annotations_numeric` / `annotations_datetime` / `annotations_y2` / `fit_linear_legend` / `fit_poly_text` / `fit_y2`)を足した(比べる要約に `bands` / `markers` / `alphas` / `annotations` / `fitlines` / `fittexts` を加えた)。 + - `helpers.py` の Phase 5b 用ヘルパー: `series_ids`、`series_state`、`state_list`、`set_fill`、`set_card_field`、`add_annotation`、`set_annotation`、`add_fit`。 - E2E は要素を id だけで選ぶ。`index.html` の id は安定させ、変えるときはテストも直す。アプリ固有の待機・操作は `tests/e2e/helpers.py` にまとめる。 - テストデータは `tests/fixtures/` の合成データだけ(公開リポジトリなので実データを置かない)。 - テスト用サーバー(`tests/e2e/server.py`)は listen backlog を 128 に広げている。既定の 5 だと、Chromium が ES モジュールを一斉に取得したときに接続が切れて、アプリが起動しないことがある。 diff --git a/README.md b/README.md index dec753b..42bdaa3 100644 --- a/README.md +++ b/README.md @@ -8,7 +8,7 @@ https://mioupa.github.io/matplotlib_gui/ を開いてください。`index.html` 1. 「入力ファイル」で `.csv` / `.txt` / `.tsv` / `.xlsx` を選ぶか、ページにファイルをドラッグ&ドロップします。Excel などでコピーした表は、「表を貼り付け」欄に貼り付けても読み込めます。 2. 読み込みと描画は自動で行われます(「描画する」ボタンはありません)。設定を変えると、すぐ再描画されます。 -3. 「描画系列」でX列・Y列・色などを選び、必要なら系列を追加します。複数のファイルを読み込んだときは、系列ごとに「データ元」を選びます。系列カードの「エラーバー」で、誤差の幅を付けられます。 +3. 「描画系列」でX列・Y列・色などを選び、必要なら系列を追加します。複数のファイルを読み込んだときは、系列ごとに「データ元」を選びます。系列カードの「エラーバー」で、誤差の幅を付けられます。点の形・不透明度・塗りつぶし帯も系列カードで選べ、系列の並べ替え(↑ ↓)と複製もできます。「注釈・解析」で、注釈と近似曲線を加えられます。 4. 「体裁」でフォント・図のサイズ・プリセットなどを整えます。 5. 「保存」でファイル名・形式・DPI を選び、「保存する」で書き出すか、「クリップボードにコピー」で他のアプリに貼り付けます。 @@ -34,6 +34,9 @@ https://mioupa.github.io/matplotlib_gui/ を開いてください。`index.html` - エラーバー: 系列ごとに、Y 方向・X 方向(棒グラフは Y 方向だけ)を「固定値」か「列で指定」から選びます。上下(左右)で別の値も指定でき、端の長さも変えられます。誤差の列が空欄・数値にできない値・負の値の点は、その点だけ描かず、警告で知らせます - 目盛の詳細: 「軸・目盛」の「X軸の目盛」「Y軸の目盛」「第2Y軸の目盛」で、主目盛の間隔(日時の X は「何日ごと」など単位つき、文字列の X は「何個おき」)、副目盛(自動・表示・なし、分割数)、数字の書式(小数の桁数・指数表記・10^n 表記)、軸の反転を指定します。対数軸では主目盛の間隔は使えません。間隔が小さすぎて目盛が 100 本を超えるときは、エラーで案内します - 上・右の枠線の表示・非表示(第2Y軸があるときは、右の枠線は消せません) +- 系列のスタイル: 点の形(丸・四角・三角・ひし形・×・+・星・なし)、不透明度、塗りつぶし帯(下端と上端の2つの列の間を塗ります。誤差の大きさではなく、値そのものを指定します)。棒グラフでは、点の形と帯は使えません。帯の列に数値にできない値があるときは、その点で帯を切り、警告で知らせます。系列は「↑」「↓」で並べ替え、「複製」でコピーできます(複製は色だけパレットの未使用の色になります) +- 注釈: 「注釈・解析」の区分で、文字・水平線・垂直線・横の帯(Y の範囲)・縦の帯(X の範囲)を図に加えます(50 個まで)。位置は軸の種類に合わせて入力します(日時の X は日付、文字列の X は何番目のカテゴリか(0 始まり))。文字は「図の中の割合」(0〜1)でも置けます。第2Y軸があるときは、Y を使う注釈を左右どちらの軸に置くか選べます。凡例名を入れた線・帯は、凡例にも出ます +- 近似曲線: 系列ごとに、最小二乗法で1次式か多項式(2〜6 次)をあてはめます(20 本まで)。式と決定係数 R² を、凡例か図の中(左上)に出せます。X が数値の系列だけが対象で、棒グラフでは使えません。対数軸でも、近似は軸の目盛ではなく元の値で行います - 保存: png / jpg / svg / pdf、背景透過。PNG・JPG は保存 DPI(72 / 150 / 300 / 600 または任意の値。既定は 300)を指定できます。プレビューは 100 dpi で表示します - PDF は文字をフォントとして埋め込みます(Type 42)。Illustrator などで文字を編集できます。SVG は、文字を「パスに変換」(既定。どの環境でも同じ見た目)か「テキストのまま」(編集できる。開く環境に同じフォントが無いと見た目が変わります)から選べます - 図のサイズ: inch / cm / mm で指定(単位を切り替えると、図の大きさを変えずに数値を換算します)