| """ |
| インタラクティブ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_file": "data.csv", |
|
|
| |
| "encoding": "utf-8", |
|
|
| |
| |
| |
| "category_columns": ["branch", "category", "rank"], |
|
|
| |
| "value_column": "count", |
|
|
| |
| |
| "title": "Branch / Category / Rank インタラクティブダッシュボード", |
|
|
| |
| "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) |
|
|
| |
| 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() |
|
|