smart-charts

👤 hanli 📦 v6.0.0 ⭐ 4.6 ⬇️ 63.5K 下載
📊 資料分析 免費

📖 技能介紹


name: smart-charts description: "Intelligent chart generation and data analysis skill. Reads user-supplied data files (CSV/Excel/JSON), analyzes data characteristics with LLM assistance, auto-recommends and generates interactive ECharts visualizations. Use when the user asks to analyze data, generate charts, create visualizations, or work with tabular data files." license: MIT compatibility: "Python 3.9+; requires pandas==3.0.1, numpy==2.4.3, openpyxl==3.1.5, xlrd==2.0.1; no network access needed (ECharts JS bundled offline); install with: pip install -r requirements.txt --require-hashes" metadata: author: smart-charts version: 6.0.0 permissions: file_read: true file_write: true network: false safety: sandbox: "LLM-generated transform code runs in a restricted sandbox (keyword blacklist + AST whitelist + safe builtins). No user confirmation required." input_formats: ["csv", "tsv", "txt", "xlsx", "xls", "json"] output_format: html max_file_size_mb: 100


Smart Charts

將資料檔案(CSV/Excel/JSON)轉化為互動式 ECharts HTML。支援 21 種圖表型別、多檔案合併、LLM 資料轉換程式碼(沙箱執行)。 CLI 細節、flags 語義、錯誤碼錶、FAQ 見 REFERENCE.md


Activation Triggers

Load this skill when any of the following is met:

  • User mentions: "analyze data", "generate chart", "data visualization", "chart", "visualization" / 使用者提到:「分析資料」「生成圖表」「資料視覺化」
  • User provides a data file and asks for analysis or visualization
  • User asks to generate charts or a report from tabular data

Hard Constraints (MUST follow)

  1. MUST follow the CLI workflow: data_parser.pycli.py,不要自寫指令碼替代 CLI。
  2. Messy headers MUST use CLI flags--skiprows N / --header-row N / --sheet,語義見 REFERENCE.md),N 由實際資料決定,不得拍腦袋固定。
  3. 列重新命名/重塑/聚合 MUST use --transform-code。解析層只解決"哪行是表頭",其餘清洗歸 transform。
  4. MUST report unsupported scenarios: CLI 確實不支援的(如巢狀 JSON 超過 1 層),先向使用者說明並給建議,不得靜默繞過。
  5. MUST NOT hard-code absolute paths in generated code; resolve paths at runtime.
  6. 不要主動傳 --lang;CLI 自動跟隨資料語言。僅當用戶明確要求某種語言時才傳。

Confirmation Policy

生成圖表是廉價可逆動作(重生成 1-10s,零外部副作用)。預設不向使用者確認,直接按資料語義選型生成。

agent 內部完成以下判斷,不打斷使用者:

  • 圖表型別:按 21 種圖表的 Required Format 匹配資料形態
  • 多檔案合併策略:按列重疊率自動決定(見 REFERENCE.md)
  • 取值口徑:按列名、單位、數值範圍推斷最可能語義

事後審閱代替事前確認:交付時必須在交付語中顯式列出本次關鍵假設,例如:

  • "選了 line 圖,因為 month 是時間序列列"
  • "多檔案按列名完全相同走縱向拼接,已注入 source_file 列"
  • "銷量按金額口徑(列含 ¥/元/amount)"

使用者審閱成品後若不同意任一假設,可一句話要求換口徑/換型別/換合併方式重生成。

小蔥技能7w4.net持續更新中。

唯一必須的使用者介入點:見 Exit Criteria 的"仍失敗"分支。


Capability Boundaries

Supported: CSV (.csv=comma / .tsv=tab / .txt=auto-detect delimiter), Excel (.xlsx/.xls), JSON (.json); 21 chart types (see below); up to ~10 files with auto-merge; single file ≤ 100 MB (≤ 50 MB recommended); auto-detects UTF-8/GBK/GB2312.

Not supported: Databases (export to CSV first), real-time/streaming data, geo maps, >100 MB files, nested JSON >1 level, non-tabular data (images/audio/video). Auto-merge requires ≥50% column overlap.

Network requirement: None. ECharts JS is bundled in assets/ and inlined into each HTML output; charts render fully offline with no external dependencies.

Security: transform 程式碼由沙箱強制校驗(黑名單 + AST 白名單 + 安全 builtins),違規會返回帶 suggestion 的結構化錯誤,按提示修正重試即可,無需使用者確認。機制細節見 REFERENCE.md。


Execution Workflow

  1. Obtain data — user uploads file(s) or provides path(s).
  2. Parse data — call data_parser.py on all files; for multiple files, assess merge feasibility.
  3. Recommend & generate — 按資料語義選型後直接生成,無需確認;交付語顯式列出關鍵假設(見 Confirmation Policy)。
  4. Transform (if needed) — raw data 不匹配目標圖表輸入格式時,生成 --transform-code
  5. Generate charts — call cli.py → ECharts HTML.
  6. Present results — 按下方 Exit Criteria 驗收後立即展示。

Exit Criteria (什麼算做完,機械可判定)

  • 成功: cli.py stdout 為 {"chart": {"success": true, ...}},且 html_path 指向的檔案存在且非空 → 立即將圖表呈現給使用者。
  • 失敗: success: false 或 exit code 1 → 讀 error.details.suggestion,修正後重試;同一環節最多重試 2 次
  • 🛑 仍失敗(唯一必須的使用者介入點): 把 code_namesuggestion、已嘗試的修復如實報告使用者並給出建議,等待使用者決策。不得靜默改用自寫指令碼兜底(違反約束 1/4)。

Data Parsing

python {skill_base}/scripts/data_parser.py <file1> [file2 ...] [--summary] [--merge] [--skiprows N] [--header-row N] [--sheet <name|index>]
  • {skill_base} = 本 skill 根目錄(含 SKILL.md)。
  • flags 的精確語義、多編碼回退、sheet 選擇細節見 REFERENCE.md。
  • Merge 關鍵 gotcha: 縱向拼接會注入 source_file 列標識來原始檔,下游 transform 程式碼必須考慮到這個額外列。≥50% 列重疊走橫向關聯;無共同結構報錯(建議分開分析)。

Chart Generation

python {skill_base}/scripts/cli.py \
  <file_path> <chart_type> \
  --title "Chart Title" --x-axis "date" --y-axis "revenue profit" \
  --transform-code "<pandas code>" --skiprows N --header-row N --sheet <name|index> \
  --lang zh|en --output-dir "./output" \
  --label-col "姓名" --color-by "地區"
  • 成功輸出 {"chart": {"success": true, "html_path": ...}} 到 stdout;失敗輸出結構化錯誤 JSON(details.suggestion 給出恢復方法)。完整引數與錯誤碼錶見 REFERENCE.md。
  • --label-col(可選):身份列(如姓名/名稱),其值進資料點的 name 和 tooltip,適用於 scatter/bubble/boxplot。不傳時自動探測未被佔用的字串列(列名含 姓名/name/id 等優先),自動選擇會記入 stdout 的 assumptions 欄位,交付語中應宣告。
  • --color-by(可選):著色列,適用於 scatter/bubble。數值列 → visualMap 連續著色;類別列 → 按類別拆 series 分色並進 legend。預設不傳——無分析意義的著色只是視覺噪音。
  • 資料點超過閾值(預設 15)時 HTML 自動啟用 dataZoom + 橫向滾動,無需 agent 處理。
  • 生成的 HTML 標題可雙擊內聯編輯(使用者可直接在瀏覽器修改標題,儲存圖片時使用新標題)。

Chart Types

選擇圖表前先核對原始資料是否匹配 Required Format;不匹配則用 transform 程式碼適配。

量綱提示:heatmap / boxplot / radar 等多列圖表,若各列量綱差異大(如滿分 10 與滿分 100 混合),需先用 transform 程式碼歸一化,否則小量綱列會被大量綱列主導。

ID Best For Trigger Keywords y_axis Cardinality Required DataFrame Format Example Columns
line Time-series trends trend, change, over time, 趨勢, 變化, 走勢 1~N 1 category/time + 1~N numeric month, productA, productB
bar Category comparison compare, rank, difference, 對比, 比較, 排名, 差異 1~N 1 category + 1~N numeric city, revenue, profit
area Cumulative change cumulative, change, 累計, 變化 1~N 1 category/time + 1~N numeric date, uv, pv
pie Composition/share share, composition, proportion, 佔比, 構成, 比例 1 1 name + 1 value category, share
scatter Correlation correlation, relationship, scatter, 相關, 關係, 散點 1 2 numeric, or 1 category + 1 numeric height, weight
radar Multi-dimension comparison multi-dimension, comprehensive, radar, 多維, 綜合, 雷達 N 1 indicator + N numeric metric, productA, productB
heatmap Density/cross-tab density, cross, matrix, heatmap, 密度, 交叉, 矩陣, 熱力 N 2 category + 1 numeric row, col, value
treemap Hierarchical proportion hierarchy, proportion, nested, 層級, 佔比, 巢狀 1 1 name + 1 value category, sales
graph Entity relationships relationship, network, topology, 關係, 網路, 拓撲 special source + target (+ value) from, to, weight
boxplot Distribution/outliers distribution, outlier, quartile, 分佈, 離群, 四分位 N N numeric math, chinese, english
waterfall Incremental change increment, change, waterfall, 增量, 變化, 瀑布 1 1 category + 1 numeric (increments) month, profit_delta
gauge KPI progress progress, kpi, achievement, 進度, KPI, 達成 1 1 numeric (mean used) completion_rate
sankey Flow transfer flow, transfer, sankey, 流向, 流量, 轉移 special source + target + value origin, destination, amount
funnel Conversion rate conversion, funnel, churn, 轉化, 漏斗, 流失 1 1 name + 1 value stage, count
sunburst Single-level proportion proportion, sunburst, 佔比, 比例 1 1 name + 1 value category, value
wordcloud Frequency/keywords word frequency, keywords, text, 詞頻, 關鍵詞, 詞雲 1 1 name + 1 value word, frequency
histogram Distribution shape distribution, histogram, 分佈, 直方圖 1 1 numeric column score
stacked_bar Composition over categories composition, stacked, 堆疊, 構成 1~N 1 category + 1~N numeric quarter, productA, productB
bubble 3-variable correlation bubble, 3-variable, 氣泡, 三變數 2 2 numeric + 1 size price, rating, sales
pareto 80/20 analysis pareto, 80/20, 帕累托, 二八 1 1 category + 1 numeric defect_type, count
combo Dual-axis comparison dual-axis, combo, 雙軸, 組合 1~N 1 category + 1 bar + 1~N line month, revenue, growth_rate

y_axis cardinality key: 1 = only first column used; 1~N = each column becomes a series; N = multiple columns expected; 2 = exactly 2 numeric columns required; special = auto-detects source/target/value columns. scatter/bubble/boxplot 中未被 x/y 佔用的字串列不會浪費——自動作為身份列進 tooltip(見 --label-col)。

Programmatic API

from scripts.chart_generator import ChartGenerator

# Single chart — returns {'chart': {'success', 'html_path'/'error', ...}}
# lang=None auto-detects from data; pass 'zh'/'en' to override (only when user asks).
result = ChartGenerator(output_dir="./output").generate_chart(
    df=df, chart_type="bar", title="Regional Revenue",
    x_axis="region", y_axis=["revenue"], lang=None,
)

# Batch — returns {'charts': [...]},每項結構與單圖一致
result = ChartGenerator(output_dir="./output").generate_multi_charts(
    df=df,
    chart_configs=[
        {"type": "bar",  "title": "Regional Revenue", "x_axis": "region", "y_axis": ["revenue"]},
        {"type": "line", "title": "Monthly Trend",   "x_axis": "month",  "y_axis": ["revenue", "profit"]},
    ],
    lang=None,
)

失敗時 successFalseerror 為結構化錯誤字典,不拋異常——檢查 success 決定下一步。


Transform Code Contract

契約(由沙箱強制,違反會收到帶 suggestion 的錯誤,按提示修正即可):

  • 可用變數只有 df, pd, np;必須產出名為 resultpd.DataFrame
  • 不要原地修改 df(用 df.copy() 或鏈式操作)
  • 原始資料已匹配目標格式時,不傳 --transform-code

Common transform patterns: - Long→multi-series: result = df.pivot_table(index='<time>', columns='<category>', values='<value>', aggfunc='sum').reset_index() - Long→pie (filter): result = df[df['metric']=='revenue'][['category','value']].rename(columns={'category':'name'}) - Wide→long: result = df.melt(id_vars=['date'], var_name='name', value_name='value') - Aggregate→bar: result = df.groupby('<category>')['<value>'].sum().reset_index() - Rename columns: result = df.rename(columns={'來源':'source','去向':'target','金額':'value'}) - Compute delta→waterfall: tmp = df.copy(); tmp['delta'] = tmp['profit'].diff().fillna(tmp['profit'].iloc[0]); result = tmp[['month','delta']] - Rename messy/uninformative column names (after --header-row leaves columns like 10分, unnamed_3): result = df.rename(columns={'unnamed_0':'student_id','unnamed_1':'name','10分':'homework_score','30分':'exam_score'}) - Forward-fill merged cells (when only the first row of a group is populated): result = df.ffill() - Combine sub-headers into a single column name (when --header-row N flattens one row but loses context): result = df.rename(columns={c: f'{c}_score' for c in df.columns if c not in ['student_id','name']})

🤖 AI 評測

這是一款質量較高的圖表生成工具,支援 CSV/Excel/JSON 等多種資料格式,能自動生成 21 種互動式圖表,且完全離線執行無需網路。文件和錯誤提示非常詳細,遇到問題能獲得明確的修復建議。內建的資料轉換沙箱機制保障了安全性。不足之處是未提供測試檔案,且部分核心程式碼檔案較大,長期維護成本可能較高。

📊 多維度評分

適應性4.7
規範性4.5
有效性4.8
可靠性4.6
可信度4.5

📁 包含檔案 (15 個)

📄 SKILL.md 13.4 KB
📄 assets/echarts-wordcloud.min.js 16.2 KB
📄 assets/echarts.min.js 1000.7 KB
📄 references/REFERENCE.md 10.4 KB
📄 requirements.txt 5.9 KB
📄 scripts/__init__.py 647 B
📄 scripts/chart_generator.py 17.1 KB
📄 scripts/cli.py 3.3 KB
📄 scripts/data_parser.py 20.1 KB
📄 scripts/data_transformer.py 14.3 KB
📄 scripts/exceptions.py 1.4 KB
📄 scripts/generate_hashes.py 5.6 KB
📄 scripts/renderers.py 32.4 KB
📄 scripts/template.py 15.4 KB
📄 scripts/ux_regression_check.py 8.4 KB