File size: 20,452 Bytes
8a7f98a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c36034a
8a7f98a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c36034a
8a7f98a
 
 
 
 
 
 
 
c36034a
8a7f98a
 
 
 
 
 
 
 
 
c36034a
8a7f98a
 
 
 
 
 
 
 
 
 
 
 
 
 
c36034a
8a7f98a
 
 
c36034a
 
 
 
 
 
8a7f98a
 
c36034a
8a7f98a
 
 
c36034a
8a7f98a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c36034a
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
"""
インタラクティブCSVビジュアライザー
=====================================
カラム名が変わっても CONFIG セクションを書き換えるだけで対応できます。
20,000行規模のデータにも対応(集計はPandasで処理)。

使い方:
    pip install pandas plotly
    python csv_visualizer.py
"""

import pandas as pd
import plotly.graph_objects as go
from plotly.subplots import make_subplots
import plotly.express as px
import json
import os

# ============================================================
#  ★ CONFIG: ここだけ書き換えれば別のCSVにも対応できます ★
# ============================================================
CONFIG = {
    # 読み込むCSVファイルのパス
    "csv_file": "data.csv",

    # CSVのエンコーディング(文字化けする場合は "shift_jis" や "cp932" に)
    "encoding": "utf-8",

    # --- カラムマッピング ---
    # カテゴリ軸(X軸・グループ軸として使う列名)を列挙する
    # ※ 順番が重要:先頭が「メイン軸」、残りが「フィルター候補」になります
    "category_columns": ["branch", "category", "rank"],

    # 集計する数値列の名前
    "value_column": "count",

    # --- 表示設定 ---
    # グラフのタイトル
    "title": "Branch / Category / Rank インタラクティブダッシュボード",

    # 出力HTMLファイル名
    "output_html": "dashboard.html",
}
# ============================================================


def load_data(cfg: dict) -> pd.DataFrame:
    """CSVを読み込む。ファイルが無ければデモデータを使う。"""
    path = cfg["csv_file"]
    if os.path.exists(path):
        df = pd.read_csv(path, encoding=cfg["encoding"])
        print(f"✓ {path} を読み込みました ({len(df):,} 行)")
    else:
        # --- デモデータ(質問に添付いただいたもの)---
        demo_csv = """branch,category,rank,count
Tokyo,A,1rank,112
Tokyo,A,3rank,45
Tokyo,B,2rank,88
Tokyo,C,1rank,57
Tokyo,D,3rank,140
Tokyo,F,1rank,19
Tokyo,G,2rank,166
Osaka,A,2rank,73
Osaka,B,1rank,128
Osaka,B,3rank,52
Osaka,D,1rank,199
Osaka,E,3rank,41
Osaka,F,2rank,77
Osaka,G,1rank,160
Nagoya,A,1rank,34
Nagoya,C,2rank,120
Nagoya,D,2rank,18
Nagoya,E,1rank,67
Nagoya,E,2rank,143
Nagoya,G,3rank,59
Fukuoka,A,3rank,84
Fukuoka,B,2rank,36
Fukuoka,C,3rank,152
Fukuoka,E,1rank,27
Fukuoka,F,3rank,99
Sapporo,A,1rank,62
Sapporo,B,3rank,115
Sapporo,D,1rank,12
Sapporo,F,2rank,173
Sapporo,G,3rank,48"""
        from io import StringIO
        df = pd.read_csv(StringIO(demo_csv))
        print("⚠ data.csv が見つからないためデモデータを使用します")
    return df


def build_filter_options(df: pd.DataFrame, cfg: dict) -> dict:
    """各カテゴリ列のユニーク値を収集する。"""
    options = {}
    for col in cfg["category_columns"]:
        if col in df.columns:
            options[col] = sorted(df[col].astype(str).unique().tolist())
    return options


def build_html(df: pd.DataFrame, cfg: dict) -> str:
    """
    Plotly を使ったインタラクティブHTMLを生成する。
    フィルター・集計・グラフ更新はすべてブラウザ内JavaScriptで処理するため
    Pythonサーバー不要・スタンドアロンHTMLとして動作する。
    """
    cat_cols = [c for c in cfg["category_columns"] if c in df.columns]
    val_col  = cfg["value_column"]

    filter_options = build_filter_options(df, cfg)

    # DataFrameをJSONとして埋め込む(20k行でも数MBなので問題なし)
    records_json = df[cat_cols + [val_col]].to_json(orient="records", force_ascii=False)

    # 色パレット
    palette = px.colors.qualitative.Set2

    html = f"""<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{cfg['title']}</title>
<script src="https://cdn.plot.ly/plotly-2.32.0.min.js"></script>
<style>
  :root {{
    --bg: #f4f6fa;
    --surface: #ffffff;
    --surface2: #f0f2f8;
    --accent: #4060d8;
    --accent2: #e07b10;
    --text: #1a1d2e;
    --text-muted: #667088;
    --border: #d8dce8;
    --radius: 10px;
  }}
  * {{ box-sizing: border-box; margin: 0; padding: 0; }}
  body {{
    background: var(--bg);
    color: var(--text);
    font-family: 'Segoe UI', 'Hiragino Sans', sans-serif;
    font-size: 14px;
    min-height: 100vh;
  }}
  header {{
    background: linear-gradient(135deg, #ffffff 0%, #eef1fb 100%);
    border-bottom: 1px solid var(--border);
    padding: 18px 28px;
    display: flex;
    align-items: center;
    gap: 14px;
  }}
  header h1 {{
    font-size: 18px;
    font-weight: 700;
    letter-spacing: 0.03em;
    color: var(--text);
  }}
  header .badge {{
    background: var(--accent);
    color: #fff;
    font-size: 11px;
    padding: 2px 10px;
    border-radius: 20px;
    font-weight: 600;
  }}
  .layout {{
    display: grid;
    grid-template-columns: 280px 1fr;
    gap: 0;
    height: calc(100vh - 61px);
  }}
  /* ---- サイドパネル ---- */
  .sidebar {{
    background: var(--surface);
    border-right: 1px solid var(--border);
    padding: 20px 16px;
    overflow-y: auto;
    display: flex;
    flex-direction: column;
    gap: 18px;
  }}
  .panel-title {{
    font-size: 11px;
    font-weight: 700;
    letter-spacing: 0.12em;
    text-transform: uppercase;
    color: var(--text-muted);
    margin-bottom: 8px;
  }}
  .filter-group {{
    background: var(--surface2);
    border: 1px solid var(--border);
    border-radius: var(--radius);
    padding: 14px;
  }}
  .filter-group label {{
    display: block;
    font-weight: 600;
    margin-bottom: 10px;
    color: var(--accent);
    font-size: 13px;
  }}
  .chip-wrap {{
    display: flex;
    flex-wrap: wrap;
    gap: 6px;
  }}
  .chip {{
    cursor: pointer;
    padding: 4px 11px;
    border-radius: 20px;
    border: 1.5px solid var(--border);
    font-size: 12px;
    color: var(--text-muted);
    background: transparent;
    transition: all 0.15s;
    user-select: none;
  }}
  .chip.active {{
    border-color: var(--accent);
    color: #fff;
    background: var(--accent);
  }}
  .chip:hover {{ border-color: var(--accent); color: var(--accent); }}
  /* count range */
  .range-row {{
    display: flex;
    gap: 8px;
    align-items: center;
  }}
  .range-row input {{
    flex: 1;
    background: #f4f6fa;
    border: 1.5px solid var(--border);
    color: var(--text);
    border-radius: 6px;
    padding: 5px 10px;
    font-size: 13px;
    width: 0;
  }}
  .range-row input:focus {{ outline: none; border-color: var(--accent); }}
  .range-sep {{ color: var(--text-muted); font-size: 12px; }}
  /* x軸選択 */
  .select-wrap select {{
    width: 100%;
    background: #f4f6fa;
    border: 1.5px solid var(--border);
    color: var(--text);
    border-radius: 6px;
    padding: 7px 10px;
    font-size: 13px;
    cursor: pointer;
  }}
  .select-wrap select:focus {{ outline: none; border-color: var(--accent); }}
  /* グラフタイプ */
  .chart-type-row {{
    display: flex;
    gap: 6px;
  }}
  .chart-btn {{
    flex: 1;
    padding: 6px;
    border-radius: 6px;
    border: 1.5px solid var(--border);
    background: transparent;
    color: var(--text-muted);
    cursor: pointer;
    font-size: 12px;
    transition: all 0.15s;
  }}
  .chart-btn.active {{
    border-color: var(--accent2);
    color: var(--accent2);
    background: rgba(245,166,35,0.1);
  }}
  /* 集計モード */
  .agg-row {{ display: flex; gap: 6px; }}
  .agg-btn {{
    flex: 1;
    padding: 5px;
    border-radius: 6px;
    border: 1.5px solid var(--border);
    background: transparent;
    color: var(--text-muted);
    cursor: pointer;
    font-size: 12px;
    transition: all 0.15s;
  }}
  .agg-btn.active {{
    border-color: var(--accent);
    color: var(--accent);
    background: rgba(108,142,245,0.1);
  }}

  /* ---- メインエリア ---- */
  .main {{
    display: flex;
    flex-direction: column;
    overflow: hidden;
    padding: 20px;
    gap: 16px;
  }}
  .stats-row {{
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 12px;
  }}
  .stat-card {{
    background: var(--surface);
    border: 1px solid var(--border);
    border-radius: var(--radius);
    padding: 14px 18px;
  }}
  .stat-card .s-label {{
    font-size: 11px;
    color: var(--text-muted);
    letter-spacing: 0.08em;
    text-transform: uppercase;
    margin-bottom: 4px;
  }}
  .stat-card .s-value {{
    font-size: 24px;
    font-weight: 700;
    color: var(--accent);
  }}
  .charts-area {{
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 16px;
    flex: 1;
    overflow: hidden;
  }}
  .chart-card {{
    background: var(--surface);
    border: 1px solid var(--border);
    border-radius: var(--radius);
    overflow: hidden;
    display: flex;
    flex-direction: column;
  }}
  .chart-card-title {{
    padding: 10px 16px;
    font-size: 12px;
    font-weight: 600;
    color: var(--text-muted);
    border-bottom: 1px solid var(--border);
    letter-spacing: 0.06em;
  }}
  .chart-card .plotly-graph {{
    flex: 1;
    min-height: 0;
  }}
  #mainChart {{ grid-column: 1 / -1; }}
  .no-data {{
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100%;
    color: var(--text-muted);
    font-size: 14px;
  }}
</style>
</head>
<body>

<header>
  <h1>{cfg['title']}</h1>
  <span class="badge">Interactive</span>
</header>

<div class="layout">
  <!-- サイドバー -->
  <aside class="sidebar">
    <div>
      <p class="panel-title">📊 表示設定</p>

      <div class="filter-group">
        <label>X軸(グループ軸)</label>
        <div class="select-wrap">
          <select id="xAxisSelect">
            {"".join(f'<option value="{c}">{c}</option>' for c in cat_cols)}
          </select>
        </div>
      </div>

      <div class="filter-group" style="margin-top:12px">
        <label>グラフタイプ</label>
        <div class="chart-type-row">
          <button class="chart-btn active" data-type="bar">棒グラフ</button>
          <button class="chart-btn" data-type="line">折れ線</button>
          <button class="chart-btn" data-type="scatter">散布図</button>
        </div>
      </div>

      <div class="filter-group" style="margin-top:12px">
        <label>集計方法</label>
        <div class="agg-row">
          <button class="agg-btn active" data-agg="sum">合計</button>
          <button class="agg-btn" data-agg="mean">平均</button>
          <button class="agg-btn" data-agg="count">件数</button>
          <button class="agg-btn" data-agg="max">最大</button>
        </div>
      </div>
    </div>

    <div>
      <p class="panel-title">🔍 フィルター</p>

      <!-- 値フィルター(カテゴリ別) -->
      {"".join(_filter_block(col, vals) for col, vals in filter_options.items())}

      <!-- countフィルター -->
      <div class="filter-group">
        <label>{val_col}(件数範囲)</label>
        <div class="range-row">
          <input type="number" id="minVal" placeholder="最小" min="0">
          <span class="range-sep">〜</span>
          <input type="number" id="maxVal" placeholder="最大" min="0">
        </div>
      </div>
    </div>

  </aside>

  <!-- メインエリア -->
  <main class="main">
    <div class="stats-row">
      <div class="stat-card"><div class="s-label">総レコード数</div><div class="s-value" id="statTotal">-</div></div>
      <div class="stat-card"><div class="s-label">フィルター後</div><div class="s-value" id="statFiltered">-</div></div>
      <div class="stat-card"><div class="s-label">{val_col} 合計</div><div class="s-value" id="statSum">-</div></div>
      <div class="stat-card"><div class="s-label">{val_col} 平均</div><div class="s-value" id="statMean">-</div></div>
    </div>

    <div class="charts-area">
      <div class="chart-card" id="mainChart">
        <div class="chart-card-title" id="mainChartTitle">メイングラフ</div>
        <div class="plotly-graph" id="plotMain"></div>
      </div>
      <div class="chart-card">
        <div class="chart-card-title">内訳(円グラフ)</div>
        <div class="plotly-graph" id="plotPie"></div>
      </div>
      <div class="chart-card">
        <div class="chart-card-title">分布(ヒストグラム)</div>
        <div class="plotly-graph" id="plotHist"></div>
      </div>
    </div>
  </main>
</div>

<script>
// ===================== データ =====================
const RAW_DATA = {records_json};
const CAT_COLS = {json.dumps(cat_cols)};
const VAL_COL  = "{val_col}";
const PALETTE  = {json.dumps(palette)};

// ===================== 状態 =====================
let state = {{
  xAxis: CAT_COLS[0],
  chartType: "bar",
  agg: "sum",
  filters: {{}},   // col -> Set of selected values (空=全選択)
  minVal: null,
  maxVal: null,
}};

// フィルターの初期化
CAT_COLS.forEach(c => {{ state.filters[c] = new Set(); }});

// ===================== ユーティリティ =====================
function fmtNum(n) {{
  if (n === null || n === undefined) return "-";
  if (Number.isInteger(n)) return n.toLocaleString();
  return n.toFixed(1);
}}

function aggregate(arr, method) {{
  if (!arr.length) return 0;
  if (method === "sum")   return arr.reduce((a,b)=>a+b, 0);
  if (method === "mean")  return arr.reduce((a,b)=>a+b, 0) / arr.length;
  if (method === "count") return arr.length;
  if (method === "max")   return Math.max(...arr);
  return 0;
}}

// ===================== フィルター処理 =====================
function getFiltered() {{
  return RAW_DATA.filter(row => {{
    for (const col of CAT_COLS) {{
      if (state.filters[col].size > 0 && !state.filters[col].has(String(row[col]))) return false;
    }}
    const v = row[VAL_COL];
    if (state.minVal !== null && v < state.minVal) return false;
    if (state.maxVal !== null && v > state.maxVal) return false;
    return true;
  }});
}}

function groupBy(data, key) {{
  const map = {{}};
  data.forEach(row => {{
    const k = String(row[key]);
    if (!map[k]) map[k] = [];
    map[k].push(row[VAL_COL]);
  }});
  return map;
}}

// ===================== グラフ描画 =====================
const PLOTLY_LAYOUT_BASE = {{
  paper_bgcolor: "transparent",
  plot_bgcolor:  "rgba(0,0,0,0.02)",
  font: {{ color: "#1a1d2e", size: 12 }},
  margin: {{ l:50, r:20, t:30, b:50 }},
  legend: {{ bgcolor: "transparent" }},
  xaxis: {{ gridcolor: "#d8dce8", zerolinecolor: "#d8dce8" }},
  yaxis: {{ gridcolor: "#d8dce8", zerolinecolor: "#d8dce8" }},
}};

function renderMain(data) {{
  const grouped = groupBy(data, state.xAxis);
  const keys = Object.keys(grouped).sort();
  const vals = keys.map(k => aggregate(grouped[k], state.agg));

  let trace;
  if (state.chartType === "bar") {{
    trace = {{
      type: "bar", x: keys, y: vals,
      marker: {{ color: vals.map((_,i) => PALETTE[i % PALETTE.length]) }},
      hovertemplate: "%{{x}}<br>%{{y:,.0f}}<extra></extra>",
    }};
  }} else if (state.chartType === "line") {{
    trace = {{
      type: "scatter", mode: "lines+markers",
      x: keys, y: vals,
      line: {{ color: "#6c8ef5", width: 2.5 }},
      marker: {{ color: PALETTE, size: 8 }},
    }};
  }} else {{
    trace = {{
      type: "scatter", mode: "markers",
      x: keys, y: vals,
      marker: {{ color: PALETTE.slice(0, keys.length), size: 14, opacity: 0.85 }},
    }};
  }}

  const layout = Object.assign({{}}, PLOTLY_LAYOUT_BASE, {{
    xaxis: Object.assign({{}}, PLOTLY_LAYOUT_BASE.xaxis, {{ title: state.xAxis }}),
    yaxis: Object.assign({{}}, PLOTLY_LAYOUT_BASE.yaxis, {{ title: `${{VAL_COL}} (${{state.agg}})` }}),
  }});

  Plotly.react("plotMain", [trace], layout, {{responsive: true, displayModeBar: false}});
  document.getElementById("mainChartTitle").textContent =
    `${{state.xAxis}} 別 ${{VAL_COL}} (${{state.agg}})`;
}}

function renderPie(data) {{
  const grouped = groupBy(data, state.xAxis);
  const keys  = Object.keys(grouped).sort();
  const vals  = keys.map(k => aggregate(grouped[k], "sum"));
  const trace = {{
    type: "pie", labels: keys, values: vals,
    marker: {{ colors: PALETTE }},
    hole: 0.38,
    hovertemplate: "%{{label}}<br>%{{value:,.0f}} (%{{percent}}<extra></extra>",
    textfont: {{ color: "#1a1d2e" }},
  }};
  const layout = Object.assign({{}}, PLOTLY_LAYOUT_BASE, {{
    margin: {{ l:20, r:20, t:20, b:20 }},
    showlegend: true,
    legend: {{ font: {{ size: 11, color: "#1a1d2e" }}, bgcolor:"transparent" }},
  }});
  Plotly.react("plotPie", [trace], layout, {{responsive: true, displayModeBar: false}});
}}

function renderHist(data) {{
  const vals  = data.map(r => r[VAL_COL]);
  const trace = {{
    type: "histogram", x: vals,
    marker: {{ color: "#6c8ef5", opacity: 0.8 }},
    hovertemplate: "%{{x}}<br>件数: %{{y}}<extra></extra>",
  }};
  const layout = Object.assign({{}}, PLOTLY_LAYOUT_BASE, {{
    xaxis: Object.assign({{}}, PLOTLY_LAYOUT_BASE.xaxis, {{ title: VAL_COL }}),
    yaxis: Object.assign({{}}, PLOTLY_LAYOUT_BASE.yaxis, {{ title: "頻度" }}),
    bargap: 0.05,
  }});
  Plotly.react("plotHist", [trace], layout, {{responsive: true, displayModeBar: false}});
}}

function updateStats(filtered) {{
  document.getElementById("statTotal").textContent    = RAW_DATA.length.toLocaleString();
  document.getElementById("statFiltered").textContent = filtered.length.toLocaleString();
  const vals = filtered.map(r => r[VAL_COL]);
  const sum  = vals.reduce((a,b) => a+b, 0);
  document.getElementById("statSum").textContent  = fmtNum(sum);
  document.getElementById("statMean").textContent = fmtNum(vals.length ? sum/vals.length : 0);
}}

function render() {{
  const filtered = getFiltered();
  updateStats(filtered);
  renderMain(filtered);
  renderPie(filtered);
  renderHist(filtered);
}}

// ===================== イベント =====================
// X軸
document.getElementById("xAxisSelect").addEventListener("change", e => {{
  state.xAxis = e.target.value;
  render();
}});

// グラフタイプ
document.querySelectorAll(".chart-btn").forEach(btn => {{
  btn.addEventListener("click", () => {{
    document.querySelectorAll(".chart-btn").forEach(b => b.classList.remove("active"));
    btn.classList.add("active");
    state.chartType = btn.dataset.type;
    render();
  }});
}});

// 集計
document.querySelectorAll(".agg-btn").forEach(btn => {{
  btn.addEventListener("click", () => {{
    document.querySelectorAll(".agg-btn").forEach(b => b.classList.remove("active"));
    btn.classList.add("active");
    state.agg = btn.dataset.agg;
    render();
  }});
}});

// チップフィルター
document.querySelectorAll(".chip").forEach(chip => {{
  chip.addEventListener("click", () => {{
    const col = chip.dataset.col;
    const val = chip.dataset.val;
    chip.classList.toggle("active");
    if (chip.classList.contains("active")) {{
      state.filters[col].add(val);
    }} else {{
      state.filters[col].delete(val);
    }}
    render();
  }});
}});

// 件数フィルター(デバウンス:入力が300ms止まったら更新)
let debounceTimer = null;
function debounceRender() {{
  clearTimeout(debounceTimer);
  debounceTimer = setTimeout(render, 300);
}}
document.getElementById("minVal").addEventListener("input", e => {{
  state.minVal = e.target.value ? Number(e.target.value) : null;
  debounceRender();
}});
document.getElementById("maxVal").addEventListener("input", e => {{
  state.maxVal = e.target.value ? Number(e.target.value) : null;
  debounceRender();
}});

// ===================== 初期描画 =====================
render();
</script>
</body>
</html>"""
    return html


def _filter_block(col: str, vals: list) -> str:
    """サイドバー用チップフィルターHTMLを生成する。"""
    chips = "".join(
        f'<span class="chip" data-col="{col}" data-val="{v}">{v}</span>'
        for v in vals
    )
    return f"""
      <div class="filter-group" style="margin-top:12px">
        <label>{col}</label>
        <div class="chip-wrap">{chips}</div>
      </div>"""


def main():
    cfg = CONFIG
    df = load_data(cfg)

    html = build_html(df, cfg)

    out = cfg["output_html"]
    with open(out, "w", encoding="utf-8") as f:
        f.write(html)
    print(f"✓ {out} を生成しました → ブラウザで開いてください")


if __name__ == "__main__":
    main()