Skip to content
Back to search

mviz

SkillWorks with Claude CodeGitHub

A chart & report builder for AI. Use when the user asks to show, display, render, or visualize data as a chart (bar, line, pie, scatter, area, bubble, histogram, etc.), a table, KPI, big number, dashboard, report, sparkline, heatmap, sankey, funnel, calendar, waterfall, or any composed data visualization. Generates compact markdown specs that render either inline (via visualize:show_widget) or as standalone HTML files (via the mviz CLI).

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today
Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/matsonj--mviz/badge.svg)](/listings/matsonj--mviz)

HTML

<a href="/listings/matsonj--mviz"><img src="/api/listings/matsonj--mviz/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

1. Connect Your Database

Connect Claude to your data using an MCP server:

- **[MotherDuck MCP](https://motherduck.com/docs/sql-reference/mcp/)** - Cloud data warehouse with DuckDB compatibility - **[Local DuckDB MCP](https://github.com/motherduckdb/mcp-server-motherduck)** - Query local `.duckdb` files, Parquet, CSV, or S3 data

If you do not have a database available, you can also load CSV files directly, although the amount of data you can fit in context can be quite limiting.

2. Add the Skill

**Claude Web or Desktop:** Download [`mviz.skill`](https://gist.github.com/matsonj/1c13b656bca20b1d2cc6260309d8eb40) and add it to your project knowledge.

**Claude Code:** Run `npx skills add matsonj/mviz` or clone this repo and work from the directory.

3. Effective Use Tips

The best analysis follows four steps:

1. **Build context** — Get the data right. Query, filter, and explore until you understand what you're looking at. 2. **Develop narrative** — What's the story? What question are you answering? What pattern matters? 3. **First pass on viz** — Create an initial visualization. Don't overthink it. 4. **Refine based on what doesn't work** — Iterate. Change chart types, adjust formatting, add context.

Start by exploring your data with natural questions. Claude writes SQL queries behind the scenes and brings the results into context:

> *"Show me revenue by region for Q4"*

> *"What are our top 10 customers by lifetime value?"*

> *"Are there any anomalies in last month's sales data?"*

Once you've built up context and are ready to visualize, tell Claude to **"use mviz to report on this analysis"**. Claude generates a polished HTML report from the data you've explored.

4. Iterate

Refine your analysis by asking follow-up questions:

> *"Change that bar chart to a line chart"*

> *"Drill into the APAC region—what's driving that spike?"*

> *"Add a table showing the top 5 products by growth rate"*

mviz Specific Guidance

mviz uses a 16-column grid.

> *"Make the bar chart wider"*

> *"Show two charts side by side at size=[8,6] each"*

> *"Make the KPIs smaller: size=[3,2] so 5 fit in a row"*

By default, it will use `size=auto` to let mviz calculate appropriate dimensions based on your data.

> [!TIP] > There are more chart types available in the library than are included in the skill.md. You can tell Claude to look at the TypeScript source for more chart types if you really need them.

Each iteration builds on your existing context. When you're done, save the HTML or print to PDF.

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

SKILL.md · Manifest · 1,122 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

  1. ---
  2. name: mviz
  3. description: A chart & report builder for AI. Use when the user asks to show, display, render, or visualize data as a chart (bar, line, pie, scatter, area, bubble, histogram, etc.), a table, KPI, big number, dashboard, report, sparkline, heatmap, sankey, funnel, calendar, waterfall, or any composed data visualization. Generates compact markdown specs that render either inline (via visualize:show_widget) or as standalone HTML files (via the mviz CLI).
  4. ---
  5. mviz v1.7.0
  6. # mviz
  7. Generate clean, data-focused charts and dashboards from compact JSON specs or markdown. Maximizes data-ink ratio with minimal chartjunk, gridlines, and decorative elements. Uses a 16-column grid layout system.
  8. ## Setup
  9. No installation required. Use `npx -y -q mviz` which auto-downloads from npm. The `-q` flag reduces npm output while still showing lint errors.
  10. For faster repeated use, install globally: `npm install -g mviz`
  11. ## What This Skill Does
  12. mviz is two things:
  13. 1. **A spec language** — markdown with fenced code blocks describing components (charts, KPIs, tables, notes, etc.). One markdown file (or a single JSON spec) describes a whole visualization.
  14. 2. **A set of renderers** that turn that spec into HTML for different display contexts. Today there are two:
  15. - **`visualize:show_widget`** (inline) — when you're in claude.ai with the visualization tool available, render the mviz spec as a `widget_code` HTML fragment using claude.ai's design system (Chart.js, `var(--color-*)` tokens). The widget appears inline in the conversation.
  16. - **mviz CLI** (standalone) — `mviz dashboard.md -o report.html` produces a complete HTML document with mviz's own design system (mdsinabox theme, ECharts). Suitable for downloads, iframe tiles, print/PDF.
  17. The mviz markdown spec is canonical; the renderer is chosen based on where the visualization will appear. Same spec, two renderings. A third-party could build a different renderer (Chart.js-based CLI, Slack-themed renderer, etc.) without changing the spec.
  18. ## Picking a renderer
  19. **Always compose the mviz markdown spec first**, even when rendering inline. The spec is the canonical artifact — emit it in a fenced code block in your response so the user can copy / reuse / pipe-to-CLI later. Then render it with whichever renderer fits the request.
  20. Before rendering, decide which renderer fits — and **state your inference** so the user can correct you. Some signals:
  21. **Inline (`visualize:show_widget`):**
  22. - "show me X" / "what was X" / "how did X change" / "render"
  23. - A small visualization (typically 1–4 components) that flows with the surrounding prose
  24. - The user is exploring data, not preparing something to share
  25. - `visualize:show_widget` is available in this conversation
  26. **Standalone (mviz CLI):**
  27. - "make a report" / "send me the file" / "export to PDF" / "save"
  28. - Multi-section composed view (5+ components, dividers, page breaks, full-width tables)
  29. - The user wants something to save, share, print, or embed in an external host (iframe tile, dashboard cell)
  30. - `visualize:show_widget` is unavailable (no inline rendering surface)
  31. Default to inline when ambiguous. State the inference explicitly:
  32. > *"I'll render this inline since you asked to see it in chat. If you'd rather a downloadable file, I can run the mviz CLI on the same spec — just say the word."*
  33. If the user later asks for the file version after an inline render, the spec is already in the conversation — pipe it through `mviz ... -o out.html` without re-composing.
  34. ## Visual Style (mdsinabox theme — for the CLI renderer)
  35. - **Font**: Helvetica Neue, Arial (clean sans-serif)
  36. - **Signature**: Orange accent line at top of dashboards
  37. - **Palette**: Blue primary, orange secondary, semantic colors (green=positive, amber=warning, red=error)
  38. - **Background**: Paper (`#f8f8f8` light) / Dark (`#231f20` dark)
  39. - **Principles**: High data-ink ratio, no chartjunk, minimal gridlines, data speaks for itself
  40. ## Renderer: mviz CLI (standalone HTML)
  41. The CLI renderer produces a complete HTML document styled in the mdsinabox theme above. Output is suitable for direct browser viewing, PDF export, iframe embedding, or sharing as a file.
  42. ### Single Chart (JSON)
  43. ```bash
  44. echo '<json_spec>' | npx -y -q mviz -o chart.html
  45. ```
  46. ### Dashboard from Markdown
  47. ```bash
  48. npx -y -q mviz dashboard.md -o dashboard.html
  49. ```
  50. ### Dashboard from Folder
  51. ```bash
  52. npx -y -q mviz my-dashboard/ -o dashboard.html
  53. ```
  54. ### Iframe-embedded output (`--embed`)
  55. When the rendered HTML will live inside another product's iframe (mdw-turbo Prism tiles, dashboard cells, etc.), pass `--embed` to strip page chrome (red accent bar, title row, theme toggle) and apply a battery of post-processes that lean the body: CSS pruning, transparent backgrounds so the host's card chrome shows through, ECharts script dropped when no charts are present, marked dropped when no `marked.parse(...)` caller, JS minify, etc.
  56. ```bash
  57. npx -y -q mviz dashboard.md --embed -o tile.html
  58. ```
  59. Embed mode emits a complete HTML document (DOCTYPE + html + head + body intact). It's not the right tool for `visualize:show_widget` — for that, use the other renderer (see below).
  60. ## 16-Column Grid System
  61. Components are sized using `size=[cols,rows]` syntax:
  62. ````markdown
  63. ```big_value size=[4,2]
  64. {"value": 1250000, "label": "Revenue", "format": "currency0m"}
  65. ```
  66. ```bar size=[8,6]
  67. {"title": "Sales", "x": "month", "y": "sales", "file": "data/sales.json"}
  68. ```
  69. ````
  70. - **16 columns** total width (both portrait and landscape)
  71. - **Row height**: ~32px per row unit (approximate - charts have padding)
  72. - **Page capacity**: Portrait [16c × 30r], Landscape [16c × 22r]
  73. - Components on same line share the row
  74. - Empty line = new row
  75. **Height Guidelines:**
  76. | Row Units | Approximate Height | Good For |
  77. |-----------|-------------------|----------|
  78. | 2 | ~64px | KPIs, single-line notes |
  79. | 4 | ~128px | Small tables, text blocks |
  80. | 5-6 | ~160-192px | Standard charts |
  81. | 8+ | ~256px+ | Dense tables, detailed charts |
  82. For charts with many categories (10+ bars, 10+ rows in dumbbell), increase row units to prevent compression.
  83. ### Side-by-Side Layout
  84. **Critical:** To place components side-by-side, their code blocks must have NO blank lines between them:
  85. ````markdown
  86. ```bar size=[8,5]
  87. {"title": "Chart A", ...}
  88. ```
  89. ```line size=[8,5]
  90. {"title": "Chart B", ...}
  91. ```
  92. ````
  93. This renders Chart A and Chart B on the same row. Adding a blank line between them would put them on separate rows.
  94. ### Headings and Section Breaks
  95. | Syntax | Effect |
  96. |--------|--------|
  97. | `# H1` | Page title |
  98. | `## H2` | Section title |
  99. | `### H3` | Light inline header (subtle, smaller text) |
  100. | `---` | Visual divider line |
  101. | `===` | Page break for printing |
  102. | `empty_space` | Invisible grid cell spacer (default 4 cols × 2 rows) |
  103. **Heading Guidelines:**
  104. - Set the page title with either the frontmatter `title:` *or* a leading `# H1`, not both.
  105. - Use `## H2` for section titles within a page (most common).
  106. - Use `### H3` for lightweight subheadings that don't interrupt flow.
  107. **Section vs Page Breaks:**
  108. - Use `---` to separate logical sections visually. Content flows naturally to the next page when needed.
  109. - Use `===` only when you explicitly want to force a new page (e.g., separating chapters or major report sections for PDF output).
  110. - Never use `===` by default. Only add page breaks when the user specifically requests them.
  111. ### Default Sizes
  112. | Component | Default Size | Notes |
  113. |-----------|-------------|-------|
  114. | `big_value` | [4, 2] | Fits 4 per row |
  115. | `delta` | [4, 2] | Fits 4 per row |
  116. | `sparkline` | [4, 2] | Compact inline chart |
  117. | `bar`, `line`, `area` | [8, 5] | Half width |
  118. | `pie`, `scatter`, `bubble` | [8, 5] | Half width |
  119. | `funnel`, `sankey`, `heatmap` | [8, 5] | Half width |
  120. | `histogram`, `boxplot`, `waterfall` | [8, 5] | Half width |
  121. | `combo` | [8, 5] | Half width |
  122. | `dumbbell` | [12, 6] | 3/4 width |
  123. | `table` | [16, 4] | Full width |
  124. | `textarea` | [16, 4] | Full width |
  125. | `calendar` | [16, 3] | Full width |
  126. | `xmr` | [16, 6] | Full width, tall |
  127. | `mermaid` | [8, 5] | Half width (use `ascii: true` for text art) |
  128. | `alert`, `note`, `text` | [16, 1] | Full width, single row |
  129. | `empty_space` | [4, 2] | Invisible spacer |
  130. ### Recommended Size Pairings
  131. | Layout Goal | Components | Sizes |
  132. |-------------|------------|-------|
  133. | 4 KPIs in a row | 4× `big_value` | [4,2] each |
  134. | 5 KPIs in a row | 4× `big_value` + 1 wider | [3,2] + [4,2] |
  135. | KPI + context | `big_value` + `textarea` | [3,2] + [13,2] |
  136. | KPI + chart | `big_value` + `bar` | [4,2] + [12,5] |
  137. ### Example: Dense KPI Row
  138. ````markdown
  139. ```big_value size=[3,2]
  140. {"value": 1250000, "label": "Revenue", "format": "currency0m"}
  141. ```
  142. ```big_value size=[3,2]
  143. {"value": 8450, "label": "Orders", "format": "num0k"}
  144. ```
  145. ```big_value size=[3,2]
  146. {"value": 2400000000, "label": "Queries", "format": "num0b"}
  147. ```
  148. ```delta size=[3,2]
  149. {"value": 0.15, "label": "MoM", "format": "pct0"}
  150. ```
  151. ```delta size=[4,2]
  152. {"value": 0.08, "label": "vs Target", "format": "pct0"}
  153. ```
  154. ````
  155. This creates a row with 5 KPIs (3+3+3+3+4 = 16 columns).
  156. ### Example: Two Charts Side by Side
  157. ````markdown
  158. ```bar size=[8,6] file=data/region-sales.json
  159. ```
  160. ```line size=[8,6] file=data/monthly-trend.json
  161. ```
  162. ````
  163. ## Supported Types
  164. **Charts:** bar, line, area, pie, scatter, bubble, boxplot, histogram, waterfall, xmr, sankey, funnel, heatmap, calendar, sparkline, combo, dumbbell, mermaid
  165. **UI Components:** big_value, delta, alert, note, text, textarea, empty_space, table
  166. ### Table Formatting
  167. Tables support column-level and cell-level formatting:
  168. **Column options:** `bold`, `italic`, `type` ("sparkline" or "heatmap")
  169. ```json
  170. {
  171. "type": "table",
  172. "columns": [
  173. {"id": "product", "title": "Product", "bold": true},
  174. {"id": "category", "title": "Category", "italic": true},
  175. {"id": "sales", "title": "Sales", "fmt": "currency"},
  176. {"id": "margin", "title": "Margin", "type": "heatmap", "fmt": "pct"},
  177. {"id": "trend", "title": "Trend", "type": "sparkline", "sparkType": "line"}
  178. ],
  179. "data": [
  180. {"product": "Widget", "category": "Electronics", "sales": 125000, "margin": 0.85, "trend": [85, 92, 88, 95, 102, 125]}
  181. ]
  182. }
  183. ```
  184. **Cell-level overrides:** Use `{"value": "text", "bold": true}` to override column defaults.
  185. **Heatmap:** Applies color gradient from low to high values. Text auto-switches to white on dark backgrounds.
  186. **Sparkline types:** `line`, `bar`, `area`, `pct_bar` (progress bar), `dumbbell` (before/after comparison)
  187. **Sort & filter:**
  188. | Field | Values | Default | Effect |
  189. |-------|--------|---------|--------|
  190. | `sortable` | `true` / `false` | `true` | Click a column header to sort. Cycles asc → desc → off. Numeric columns sort by raw value. |
  191. | `filter` | `true` / `false` | `false` | When true, render a "Filter by any value…" search input above the table. Rows filter live on case-insensitive contains match across all cells. |
  192. Example: `{"type": "table", "filter": true, "columns": [...], "data": [...]}`
  193. ### Note Types
  194. Notes support three severity levels via `noteType`:
  195. | Type | Border Color | Use For |
  196. |------|--------------|---------|
  197. | `default` | Red | Important notices (default) |
  198. | `warning` | Yellow | Cautions, preliminary data |
  199. | `tip` | Green | Best practices, pro tips |
  200. Notes also support an optional `label` for bold prefix text:
  201. ```json
  202. {"type": "note", "label": "Pro Tip:", "content": "Use keyboard shortcuts for faster navigation.", "noteType": "tip"}
  203. ```
  204. ### Specialized Chart Examples
  205. **big_value** - Hero metrics with large display:
  206. ```json
  207. {"type": "big_value", "value": 1250000, "label": "Revenue", "format": "currency0m"}
  208. ```
  209. - Optional `comparison` object: `{"value": 10300, "format": "currency", "label": "vs last month"}` shows change with arrow
  210. **dumbbell** - Before/after comparisons with directional coloring:
  211. ```json
  212. {
  213. "type": "dumbbell",
  214. "title": "ELO Changes",
  215. "category": "team",
  216. "start": "before",
  217. "end": "after",
  218. "startLabel": "Week 1",
  219. "endLabel": "Week 2",
  220. "higherIsBetter": true,
  221. "data": [
  222. {"team": "Chiefs", "before": 1650, "after": 1720},
  223. {"team": "Bills", "before": 1600, "after": 1550}
  224. ]
  225. }
  226. ```
  227. - Green = improvement, Red = decline, Grey = no change
  228. - `higherIsBetter: false` for rankings (lower = better)
  229. - Labels auto-abbreviate large numbers (7450 → "7k")
  230. **delta** - Change metrics with directional coloring:
  231. ```json
  232. {"type": "delta", "value": 0.15, "label": "MoM Growth", "format": "pct0"}
  233. ```
  234. - Positive values show green with ▲, negative show red with ▼
  235. - Optional `comparison` object: `{"value": 0.05, "label": "vs Target"}`
  236. **area** - Filled line chart for cumulative/volume data:
  237. ```json
  238. {
  239. "type": "area",
  240. "title": "Daily Active Users",
  241. "x": "date",
  242. "y": "users",
  243. "data": [{"date": "Mon", "users": 1200}, {"date": "Tue", "users": 1450}]
  244. }
  245. ```
  246. **combo** - Bar + line with dual Y-axis:
  247. ```json
  248. {
  249. "type": "combo",
  250. "title": "Revenue vs Growth Rate",
  251. "x": "quarter",
  252. "y": ["revenue", "growth_rate"],
  253. "data": [
  254. {"quarter": "Q1", "revenue": 1000000, "growth_rate": 0.15},
  255. {"quarter": "Q2", "revenue": 1200000, "growth_rate": 0.20}
  256. ]
  257. }
  258. ```
  259. - First y-field renders as bars, second as line
  260. - Dual Y-axes with independent scales
  261. **heatmap** - 2D matrix visualization:
  262. ```json
  263. {
  264. "type": "heatmap",
  265. "title": "Activity by Hour",
  266. "xCategories": ["Mon", "Tue", "Wed", "Thu", "Fri"],
  267. "yCategories": ["9am", "12pm", "3pm", "6pm"],
  268. "format": "num0",
  269. "data": [[0, 0, 85], [1, 0, 90], [2, 0, 72]]
  270. }
  271. ```
  272. - `format` option applies to cell labels (e.g., `num0k`, `currency0k`, `pct`)
  273. **funnel** - Conversion or elimination flows:
  274. ```json
  275. {
  276. "type": "funnel",
  277. "title": "Sales Pipeline",
  278. "format": "num0",
  279. "data": [
  280. {"stage": "Leads", "value": 1000},
  281. {"stage": "Qualified", "value": 600},
  282. {"stage": "Proposal", "value": 300},
  283. {"stage": "Closed", "value": 100}
  284. ]
  285. }
  286. ```
  287. - `format` option applies to labels/tooltips (e.g., `currency_auto`, `pct`, `num0`)
  288. **waterfall** - Cumulative change visualization:
  289. ```json
  290. {
  291. "type": "waterfall",
  292. "title": "Revenue Bridge",
  293. "x": "item",
  294. "y": "value",
  295. "data": [
  296. {"item": "Start", "value": 1000, "isTotal": true},
  297. {"item": "Growth", "value": 200},
  298. {"item": "Churn", "value": -50},
  299. {"item": "End", "value": 1150, "isTotal": true}
  300. ]
  301. }
  302. ```
  303. **bubble** - Scatter with size dimension. Supports `series` for color grouping and `showLabels` for persistent labels:
  304. ```json
  305. {
  306. "type": "bubble",
  307. "title": "Market Analysis",
  308. "x": "growth",
  309. "y": "profit",
  310. "size": "revenue",
  311. "series": "region",
  312. "label": "company",
  313. "data": [
  314. {"growth": 5, "profit": 20, "revenue": 100, "region": "US", "company": "Acme"},
  315. {"growth": 10, "profit": 15, "revenue": 200, "region": "EU", "company": "Beta"}
  316. ]
  317. }
  318. ```
  319. **sankey** - Flow diagrams showing relationships:
  320. ```json
  321. {
  322. "type": "sankey",
  323. "title": "Traffic Sources",
  324. "data": [
  325. {"source": "Organic", "target": "Landing", "value": 500},
  326. {"source": "Paid", "target": "Landing", "value": 300},
  327. {"source": "Landing", "target": "Signup", "value": 400}
  328. ]
  329. }
  330. ```
  331. **mermaid** - Diagrams from Mermaid syntax (flowcharts, sequence, state, class, ER). Use array for multi-line code:
  332. ```json
  333. {
  334. "type": "mermaid",
  335. "title": "User Flow",
  336. "code": [
  337. "graph TD",
  338. " A[Start] --> B{Decision}",
  339. " B -->|Yes| C[Action]",
  340. " B -->|No| D[End]"
  341. ]
  342. }
  343. ```
  344. **mermaid (ASCII)** - ASCII/Unicode text-based diagrams (set `ascii: true`):
  345. ```json
  346. {
  347. "type": "mermaid",
  348. "title": "Process Flow",
  349. "code": ["graph LR", " A[Input] --> B[Process] --> C[Output]"],
  350. "ascii": true
  351. }
  352. ```
  353. **Mermaid lint rules** (errors that will fail validation):
  354. - No `<br/>` tags in labels (render as literal text, not line breaks)
  355. - No quoted labels like `A["text"]` in flowcharts (quotes appear in output)
  356. ## Number Format Options
  357. | Format | Example | Use For |
  358. |--------|---------|---------|
  359. | `auto` | 1.000m, 10.00k | **Smart auto-format (recommended)** |
  360. | `currency_auto` | $1.000m, $10.00k | Smart auto-format with $ prefix |
  361. | `currency0m` | $1.2m | Millions |
  362. | `currency0b` | $1.2b | Billions |
  363. | `currency0k` | $125k | Thousands |
  364. | `currency` | $1,250,000 | Detailed amounts |
  365. | `num0m` | 1.2m | Millions |
  366. | `num0b` | 1.2b | Billions |
  367. | `num0k` | 125k | Thousands |
  368. | `num0` | 1,250,000 | Detailed counts |
  369. | `pct` | 15.0% | Percentage with decimal |
  370. | `pct0` | 15% | Percentage integer |
  371. | `pct1` | 15.0% | Percentage with 1 decimal |
  372. | `date` | 2026-02-24 | Date column — string values pass through; numeric epoch ms render as `YYYY-MM-DD`. Tables sort by epoch ms. |
  373. | `duration` | 1m7s | Duration column — numeric seconds render as `1m7s` / `25m39s`; strings pass through. Tables sort by total seconds. |
  374. **Percentage formats:** `pct`, `pct0`, `pct1` always multiply by 100 for scalar components (`big_value`, `delta`) — pass `0.15` for `15%`. Charts and tables are **series-aware**: they inspect the column/series and skip the multiply when any value exceeds 1, so `[15, 22, 18]` renders as `15.0%`, `22.0%`, `18.0%` (not `1500%+`) while `[0.15, 0.22, 0.18]` still renders as `15.0%`, `22.0%`, `18.0%`. Pass `[0.8, 1.2]` for a growth-rate series and it'll render as `80%`, `120%`. If `big_value` / `delta` get a pct value > 1, the linter warns "did you mean value/100?".
  375. **Smart formatting (`auto`/`currency_auto`) is recommended.** The `format` option applies to both axis labels and data labels on bar charts. It automatically picks the right suffix (k, m, b) based on magnitude and always shows 4 significant digits. Negative values are wrapped in parentheses: `(1.000m)`.
  376. When no format is specified, smart formatting is used by default.
  377. ### Auto-Detected Axis Formatting
  378. Chart axes automatically detect the appropriate format based on field names:
  379. | Field Pattern | Auto Format | Example |
  380. |---------------|-------------|---------|
  381. | revenue, sales, price, cost, profit, amount | `currency_auto` | $1.250m |
  382. | pct, percent, rate, ratio | `pct` | 15.0% |
  383. | All other numeric fields | `auto` | 1.250m |
  384. Override with an explicit `format` field in the chart spec.
  385. ## Columnar Data Format
  386. The chart generator auto-detects columnar query results. Instead of manually converting `columns`/`rows` to `data`, pass the result directly:
  387. ```json
  388. {
  389. "type": "bar",
  390. "title": "Sales by Region",
  391. "x": "region",
  392. "y": "sales",
  393. "columns": ["region", "sales"],
  394. "rows": [["North", 45000], ["South", 32000], ["East", 28000]]
  395. }
  396. ```
  397. This is automatically converted internally. No manual JSON reconstruction needed.
  398. ## Axis Bounds (yMin/yMax)
  399. For line, area, bar, and combo charts, control y-axis range with `yMin` and `yMax`:
  400. ```json
  401. {
  402. "type": "line",
  403. "title": "Elo Rating Trend",
  404. "x": "date",
  405. "y": "elo",
  406. "yMin": 1400,
  407. "data": [{"date": "Oct", "elo": 1511}, {"date": "Jan", "elo": 1636}]
  408. }
  409. ```
  410. Use `yMin` when:
  411. - Data doesn't start at 0 (ratings, stock prices, temperatures)
  412. - You want to emphasize relative changes over absolute values
  413. Use `yMax` when:
  414. - Labels are being cut off at the top of the chart
  415. - You need headroom above the highest data point
  416. ## Validation & Lint Rules
  417. The CLI validates specs automatically using built-in lint rules. Use `--lint` flag for validation-only mode:
  418. ```bash
  419. npx -y -q mviz --lint dashboard.md # Validate without generating HTML
  420. ```
  421. ### Lint Rules
  422. | Rule | Severity | Trigger |
  423. |------|----------|---------|
  424. | `required-fields` | warning | Missing required fields like `x`, `y`, or `data` |
  425. | `unknown-field` | warning | Field not recognized for the chart type |
  426. | `time-series-sorted` | error | Time series data not in chronological order |
  427. | `sankey-wrong-keys` | error | Using `from`/`to` instead of `source`/`target` |
  428. | `big-value-string` | error | Passing `"62.5%"` string instead of `0.625` number |
  429. | `duplicate-x-values` | warning | Duplicate values on x-axis |
  430. | `mermaid-no-br-tags` | error | `<br/>` tags in mermaid code (render as literal text) |
  431. | `mermaid-no-quoted-labels` | error | Quoted labels like `A["text"]` in flowcharts |
  432. **Errors** exit with code 1. **Warnings** log to stderr but don't fail.
  433. ### Common Fixes
  434. **Time series error:** Sort your data by date before passing to the chart.
  435. **Sankey wrong keys:** Use `source`, `target`, `value` in your data:
  436. ```json
  437. {"source": "A", "target": "B", "value": 100}
  438. ```
  439. **big_value string:** Pass numeric value with format option:
  440. ```json
  441. {"type": "big_value", "value": 0.625, "format": "pct0", "label": "Rate"}
  442. ```
  443. ## Troubleshooting
  444. ### Warning Messages
  445. The generator outputs helpful warnings to stderr when issues are detected:
  446. | Warning | Cause | Solution |
  447. |---------|-------|----------|
  448. | `Invalid JSON in 'bar' block` | Malformed JSON syntax | Check JSON syntax, ensure proper quoting |
  449. | `Unknown component type 'bars'` | Typo in chart type | Use suggested type (e.g., `bar` not `bars`) |
  450. | `Cannot resolve 'file=...'` | File reference without base directory | Use file path argument or inline JSON |
  451. | `Row exceeds 16 columns` | Too many components in one row | Reduce component widths or split into rows |
  452. Warnings include context like content previews, similar type suggestions, and section/row info.
  453. ### Labels Cut Off at Chart Edges
  454. If data labels on bar, line, or area charts are being cut off at the top:
  455. 1. Find the maximum value in your data
  456. 2. Set `yMax` to ~10-15% higher than that value
  457. **Example:** If max value is 200, set `"yMax": 220`
  458. ```json
  459. {
  460. "type": "bar",
  461. "title": "Sales",
  462. "x": "month",
  463. "y": "sales",
  464. "yMax": 250,
  465. "data": [{"month": "Jan", "sales": 180}, {"month": "Feb", "sales": 220}]
  466. }
  467. ```
  468. This provides headroom for the label text above the bars.
  469. ## Data Generation Best Practice
  470. **Use SQL to generate data files** instead of manually authoring JSON. This reduces errors and ensures data accuracy:
  471. ```sql
  472. -- Generate chart data file
  473. COPY (
  474. SELECT month, SUM(sales) as sales, SUM(revenue) as revenue
  475. FROM orders
  476. GROUP BY month
  477. ORDER BY month
  478. ) TO 'data/monthly-sales.json' (FORMAT JSON, ARRAY true);
  479. ```
  480. Then reference the generated file:
  481. ````markdown
  482. ```bar file=data/monthly-sales.json
  483. {"title": "Monthly Sales", "x": "month", "y": "sales"}
  484. ```
  485. ````
  486. This approach:
  487. - Ensures data accuracy (no manual transcription errors)
  488. - Keeps data in sync with source systems
  489. - Reduces token usage (SQL is more compact than JSON arrays)
  490. - Makes updates easy (re-run query to refresh)
  491. ## File References (JSON and CSV)
  492. Reference external data files to save tokens and enable data/visualization separation:
  493. ### JSON Files
  494. ````markdown
  495. ```bar size=[8,6] file=data/sales.json
  496. ```
  497. ````
  498. ### CSV Files (DuckDB Workflow)
  499. CSV files work great with DuckDB for data exploration:
  500. ```bash
  501. # Export query results to CSV
  502. duckdb -csv -c "SELECT quarter, revenue FROM sales" > data/quarterly.csv
  503. ```
  504. ````markdown
  505. ```bar file=data/quarterly.csv
  506. {"title": "Quarterly Revenue", "x": "quarter", "y": "revenue"}
  507. ```
  508. ````
  509. - **CSV provides data**, inline JSON provides chart options (title, x, y, format)
  510. - **Auto-detection**: If no inline options, first column = x, second column = y
  511. - **Type conversion**: Numeric strings auto-convert to int/float
  512. ### Benefits of File References
  513. | Approach | Best For |
  514. |----------|----------|
  515. | Inline JSON | Small, static specs |
  516. | JSON files | Reusable chart configs |
  517. | CSV files | DuckDB workflows, frequently updated data |
  518. ## Dashboard Markdown Format
  519. ````markdown
  520. ---
  521. theme: light
  522. title: My Dashboard
  523. ---
  524. # Page Title
  525. ## Section Name
  526. ```big_value size=[4,2]
  527. {"value": 125000, "label": "Revenue", "format": "currency0k"}
  528. ```
  529. ```bar size=[12,6] file=data/sales.json
  530. ```
  531. ````
  532. **Rules:**
  533. - `# Title` sets the page title (first occurrence only)
  534. - `## Section` creates a new section with divider (border, spacing)
  535. - `### Header` creates a soft header within the current section (no divider)
  536. - `---` creates a section break (untitled, visual divider only)
  537. - `===` creates a page break (forces new page when printing to PDF)
  538. - `size=[cols,rows]` controls layout (16-column grid)
  539. - `size=auto` auto-calculates size from data
  540. - `file=path` references external JSON
  541. - Empty lines = new rows
  542. ## Theme Toggle
  543. Dashboards include a theme toggle button (top right) that switches between light and dark modes. All charts dynamically update when the theme changes.
  544. Set the default theme in frontmatter:
  545. ```yaml
  546. ---
  547. title: My Dashboard
  548. theme: dark
  549. orientation: landscape
  550. print: true
  551. ---
  552. ```
  553. | Option | Description |
  554. |--------|-------------|
  555. | `title` | Dashboard title displayed at top |
  556. | `theme` | `light` (default) or `dark` |
  557. | `orientation` | `portrait` (default) or `landscape` for print layout |
  558. | `print` | When `true`, requires explicit `size=[cols,rows]` on all components |
  559. | `continuous` | When `true`, removes section breaks between `#` headers for flowing layout |
  560. | `embed` | When `true`, strips page chrome (red accent bar, title row, theme toggle) so the output can be tucked inside another host's frame (iframe tile, dashboard cell). Also available as the `--embed` CLI flag. |
  561. **Page capacity:** Portrait fits 30 row units, landscape fits 22 row units (Letter paper, 0.5" margins).
  562. The theme toggle affects all charts globally - individual chart `theme` settings are ignored in favor of the global toggle.
  563. ## Renderer: `visualize:show_widget` (inline)
  564. The show_widget renderer lives inside Claude. Claude reads the mviz spec, translates it to a `widget_code` HTML fragment using claude.ai's design system (Chart.js + `var(--color-*)` tokens), and passes it to `visualize:show_widget`. The widget appears inline in the conversation.
  565. ### Workflow
  566. 1. **Compose the mviz markdown spec** and emit it visibly in your response, in a fenced code block. The spec is the canonical artifact — even when the user only wants an inline render, write the spec down so it's available for later (copy / reuse / pipe-to-CLI). Then render below it.
  567. ```markdown
  568. ```mviz
  569. ---
  570. title: Q3 sales
  571. ---
  572. ```big_value
  573. {"value": 1250000, "label": "Q3 Revenue", "format": "currency_auto"}
  574. ```
  575. ...
  576. ```
  577. 2. **State your renderer inference**, one short sentence. Example: *"Rendering inline since you asked to see it in chat — say the word if you want the file too."*
  578. 3. **Translate the spec to `widget_code`** following the mapping tables below. Use claude.ai's design tokens (`var(--color-*)`), Chart.js for charts, metric cards for KPIs.
  579. 4. **Call `visualize:show_widget`** with the `widget_code`.
  580. 5. **Write the surrounding explanation as normal response text**, outside the tool call. The widget is the visual; your prose carries the meaning.
  581. ### When this renderer is the right pick
  582. Trigger inline rendering when **all** of these hold:
  583. - The user is in claude.ai web/desktop (not Claude Code, not the API).
  584. - `visualize:show_widget` is in your available tools.
  585. - The visualization is composed of mviz component types that have chat-native equivalents (see mapping below).
  586. - The visualization is small enough to emit naturally as `widget_code` — model emit time dominates latency, so 6–8 components is comfortable, 15+ starts to feel slow.
  587. If any of those fails — mviz-only chart types like sankey/heatmap, very large dashboards, no `show_widget` — render through the mviz CLI instead and offer the file as a follow-up.
  588. ### What the show_widget renderer is NOT
  589. - **Not the mviz CLI.** Don't invoke `npx mviz` to produce HTML for `show_widget`. The CLI's mdsinabox-styled output doesn't match the chat host, and the subprocess + larger emit costs latency. The CLI is a *peer renderer* used for standalone files.
  590. - **Not a paste-mviz-output-into-widget_code path.** mviz CLI emits a complete document with its own design system; that wouldn't render correctly inside the widget sandbox even if `show_widget` accepted documents (it doesn't — it requires fragments).
  591. ### The translation: mviz spec → claude.ai-native HTML
  592. mviz markdown describes structure. Read the spec, then write a `widget_code` HTML fragment using claude.ai's design system.
  593. **Component type mapping**
  594. | mviz type | claude.ai-native rendering |
  595. |---|---|
  596. | `big_value` | Metric card: surface card with `--color-text-secondary` 13px label above, 24px / weight 500 number below |
  597. | `delta` | Metric card variant with colored sign (`--color-success` / `--color-danger`) + arrow glyph |
  598. | `bar` | Chart.js `type: 'bar'` |
  599. | `line` | Chart.js `type: 'line'` |
  600. | `area` | Chart.js `type: 'line'` with `fill: true` |
  601. | `pie` | Chart.js `type: 'pie'`. If the mviz spec sets `donut: true`, render as Chart.js `type: 'doughnut'` instead (mviz exposes donut as a *flag* on the pie type, not a separate component). |
  602. | `scatter` | Chart.js `type: 'scatter'` |
  603. | `bubble` | Chart.js `type: 'bubble'` |
  604. | `histogram` | Chart.js `type: 'bar'` over pre-bucketed data |
  605. | `sparkline` | Inline `<svg>` (3–5 line-width strokes) — too small to justify Chart.js |
  606. | `table` | HTML `<table>` with `border-collapse: collapse`, `0.5px solid var(--color-border-tertiary)`, header row in `--color-background-secondary` |
  607. | `note`, `alert` | Bordered callout: `border-left: 3px solid var(--color-{info,warning,success,danger})`, padding 8px 12px, label + body text |
  608. | `text`, `textarea` | Render the markdown content as prose **in your response text outside the tool call** — not inside the widget. The `visualize:read_me` design guide is explicit: text goes in the response, visuals go in the tool. |
  609. | `empty_space` | An empty grid cell — produce `<div></div>` with the right `grid-column: span N` |
  610. | `boxplot`, `waterfall`, `xmr`, `sankey`, `funnel`, `heatmap`, `calendar`, `combo`, `dumbbell`, `mermaid` | No clean Chart.js equivalent. If the visualization centers on one of these, fall back to a standalone `mviz` export and don't render inline. |
  611. **Layout mapping**
  612. mviz uses a 16-col grid with explicit `size=[cols, rows]` directives. Inside a 680px-wide `show_widget` container, that translates to:
  613. ```css
  614. .mviz-grid {
  615. display: grid;
  616. grid-template-columns: repeat(16, 1fr);
  617. gap: 8px;
  618. }
  619. .mviz-grid > .item-12 { grid-column: span 12; }
  620. .mviz-grid > .item-8 { grid-column: span 8; }
  621. .mviz-grid > .item-4 { grid-column: span 4; }
  622. ```
  623. For simple 2–3 component widgets you can also use claude.ai's recommended responsive pattern:
  624. ```css
  625. display: grid;
  626. grid-template-columns: repeat(auto-fit, minmax(160px, 1fr));
  627. gap: 12px;
  628. ```
  629. This auto-fits to the host's chosen width, which is the right choice when the exact column count is not load-bearing.
  630. **Format hint mapping**
  631. mviz format strings → JS formatters used inside Chart.js label/tooltip callbacks and metric-card text:
  632. | mviz `fmt` | JS expression (assume `v` is the number) |
  633. |---|---|
  634. | `currency_auto`, `auto` | Use the helper below — the smart-format contract has magnitude tiers that don't fit on one line |
  635. | `currency` | `'$' + v.toLocaleString('en-US')` (e.g. `1250000` → `$1,250,000`) |
  636. | `currency0k` | `'$' + Math.round(v/1000) + 'k'` (e.g. `125000` → `$125k`) |
  637. | `currency0m` | `'$' + (v/1e6).toFixed(1) + 'm'` (e.g. `1250000` → `$1.2m`) |
  638. | `pct`, `pct1` | `(v * 100).toFixed(1) + '%'` — mviz multiplies pct by 100, so pass the decimal (`0.15` → `15.0%`). For chart series mviz auto-detects whether values are already in pct units; mirror that if the data is ambiguous. |
  639. | `pct0` | `Math.round(v * 100) + '%'` (e.g. `0.15` → `15%`) |
  640. | `num0` | `v.toLocaleString('en-US')` (e.g. `1250` → `1,250`) |
  641. | `num1` | `v.toFixed(1)` (e.g. `1.234` → `1.2`) |
  642. | `num0k` | `Math.round(v/1000) + 'k'` (e.g. `1250` → `1k`) |
  643. The `currency_auto` / `auto` helper, mirroring mviz's `smartFormatNumber`. ~4 significant digits, magnitude tier with suffix, negatives in parentheses — match these exact thresholds so the inline render and the standalone report show identical numbers:
  644. ```js
  645. function fmtAuto(v, sym = '') {
  646. const neg = v < 0, abs = Math.abs(v);
  647. let s;
  648. if (abs >= 1e9) {
  649. const x = abs / 1e9;
  650. s = sym + (x >= 100 ? x.toFixed(1) : x >= 10 ? x.toFixed(2) : x.toFixed(3)) + 'b';
  651. } else if (abs >= 1e6) {
  652. const x = abs / 1e6;
  653. s = sym + (x >= 100 ? x.toFixed(1) : x >= 10 ? x.toFixed(2) : x.toFixed(3)) + 'm';
  654. } else if (abs >= 1e4) {
  655. const x = abs / 1e3;
  656. s = sym + (x >= 100 ? x.toFixed(1) : x.toFixed(2)) + 'k';
  657. } else if (abs >= 1e3) {
  658. s = sym + abs.toLocaleString('en-US', { maximumFractionDigits: 0 });
  659. } else {
  660. s = sym + (abs === Math.floor(abs) ? abs : abs.toFixed(2));
  661. }
  662. return neg ? '(' + s + ')' : s;
  663. }
  664. // currency_auto: fmtAuto(v, '$') → 1_250_000 → "$1.250m", 12_500 → "$12.50k", 1_250 → "$1,250"
  665. // auto: fmtAuto(v) → 1_250_000 → "1.250m", 12_500 → "12.50k", 1_250 → "1,250"
  666. ```
  667. Always `Math.round` / `.toFixed(n)` displayed numbers — `0.1 + 0.2` is `0.30000000000000004` and that artifact will leak into the widget if you don't.
  668. **Color mapping**
  669. Chart.js renders to `<canvas>` and cannot resolve CSS variables. Use hardcoded hex from claude.ai's color ramps (the `c-{ramp}` stops listed in the `visualize:read_me` design module). A safe default palette for mviz series:
  670. - Primary (mviz blue `#0777b3`) → `c-blue` 600 `#185FA5`
  671. - Secondary (mviz orange `#bd4e35`) → `c-coral` 600 `#993C1D`
  672. - Positive (mviz green `#2d7a00`) → `c-green` 600 `#3B6D11`
  673. - Warning (mviz amber `#e18727`) → `c-amber` 600 `#854F0B`
  674. - Error (mviz red `#bc1200`) → `c-red` 600 `#A32D2D`
  675. - Tertiary / neutral → `c-gray` 600 `#5F5E5A`
  676. For HTML elements (cards, table borders, text), use `var(--color-text-primary)` / `var(--color-background-secondary)` / `var(--color-border-tertiary)` and friends — they auto-adapt to dark mode.
  677. ### Chart.js setup (canonical patterns from `visualize:read_me`)
  678. ```html
  679. <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.4.1/chart.umd.js"></script>
  680. ```
  681. Wrap every canvas in a sized div:
  682. ```html
  683. <div style="position: relative; width: 100%; height: 240px;">
  684. <canvas id="c1" role="img" aria-label="Sales by region — NA $540k, EU $380k, APAC $220k, LATAM $110k">
  685. Sales by region (bar chart). NA 540, EU 380, APAC 220, LATAM 110.
  686. </canvas>
  687. </div>
  688. ```
  689. Constraints to honor:
  690. - `responsive: true, maintainAspectRatio: false` — height goes on the wrapper div only, never on the canvas itself.
  691. - Horizontal bar charts: wrapper height ≥ `(bars * 40) + 80` px.
  692. - ≤12 categories where every label must be visible: `scales.x.ticks: { autoSkip: false, maxRotation: 45 }`.
  693. - Bubble/scatter: pad `scales.{x,y}.{min,max}` ~10 % beyond data range so radii don't clip.
  694. - Negative currency: `-$5M` not `$-5M` — sign before symbol. Use a formatter `(v) => (v < 0 ? '-' : '') + '$' + Math.abs(v) + 'M'`.
  695. Default Chart.js legends use round dots and no values — disable them and emit your own legend as inline HTML (small color squares, tight spacing, include the value/percentage when categorical):
  696. ```js
  697. plugins: { legend: { display: false } }
  698. ```
  699. ```html
  700. <div style="display: flex; flex-wrap: wrap; gap: 16px; margin-bottom: 8px;
  701. font-size: 12px; color: var(--color-text-secondary);">
  702. <span style="display: flex; align-items: center; gap: 4px;">
  703. <span style="width: 10px; height: 10px; border-radius: 2px; background: #185FA5;"></span>NA $540k
  704. </span>
  705. <!-- repeat -->
  706. </div>
  707. ```
  708. ### Metric card (for `big_value` and `delta`)
  709. ```html
  710. <div style="background: var(--color-background-secondary); border-radius: var(--border-radius-md);
  711. padding: 1rem;">
  712. <div style="font-size: 13px; color: var(--color-text-secondary);">Q3 Revenue</div>
  713. <div style="font-size: 24px; font-weight: 500; color: var(--color-text-primary);
  714. line-height: 1; margin-top: 4px;">$1.250m</div>
  715. </div>
  716. ```
  717. Use in grids of 2–4 with `gap: 12px`. For `delta`, add a small directional indicator with `color: var(--color-success)` or `var(--color-danger)`.
  718. ### Worked example
  719. Spec (mviz markdown):
  720. ````markdown
  721. ---
  722. title: Q3 sales
  723. ---
  724. ```big_value size=[4,2]
  725. {"value": 1250000, "label": "Q3 Revenue", "format": "currency_auto"}
  726. ```
  727. ```big_value size=[4,2]
  728. {"value": 0.184, "label": "Growth", "format": "pct1"}
  729. ```
  730. ```bar size=[16,5]
  731. {"title": "Sales by region", "x": "region", "y": "sales", "format": "currency0k",
  732. "data": [{"region":"NA","sales":540000},{"region":"EU","sales":380000},
  733. {"region":"APAC","sales":220000},{"region":"LATAM","sales":110000}]}
  734. ```
  735. ````
  736. Inline render (the `widget_code` you pass to `visualize:show_widget`):
  737. ```html
  738. <h2 class="sr-only">Q3 sales overview: $1.250m revenue, 18.4% growth, regional breakdown.</h2>
  739. <div style="display: grid; grid-template-columns: repeat(16, 1fr); gap: 12px;">
  740. <div style="grid-column: span 4; background: var(--color-background-secondary);
  741. border-radius: var(--border-radius-md); padding: 1rem;">
  742. <div style="font-size: 13px; color: var(--color-text-secondary);">Q3 Revenue</div>
  743. <div style="font-size: 24px; font-weight: 500; margin-top: 4px;">$1.250m</div>
  744. </div>
  745. <div style="grid-column: span 4; background: var(--color-background-secondary);
  746. border-radius: var(--border-radius-md); padding: 1rem;">
  747. <div style="font-size: 13px; color: var(--color-text-secondary);">Growth</div>
  748. <div style="font-size: 24px; font-weight: 500; margin-top: 4px;
  749. color: var(--color-success);">+18.4%</div>
  750. </div>
  751. <div style="grid-column: span 16;">
  752. <div style="font-size: 14px; font-weight: 500; margin-bottom: 8px;">Sales by region</div>
  753. <div style="position: relative; width: 100%; height: 240px;">
  754. <canvas id="mviz-bar-1" role="img"
  755. aria-label="Sales by region — NA $540k, EU $380k, APAC $220k, LATAM $110k">
  756. NA 540, EU 380, APAC 220, LATAM 110.
  757. </canvas>
  758. </div>
  759. </div>
  760. </div>
  761. <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.4.1/chart.umd.js"></script>
  762. <script>
  763. new Chart(document.getElementById('mviz-bar-1'), {
  764. type: 'bar',
  765. data: {
  766. labels: ['NA', 'EU', 'APAC', 'LATAM'],
  767. datasets: [{ label: 'Sales', data: [540000, 380000, 220000, 110000], backgroundColor: '#185FA5' }],
  768. },
  769. options: {
  770. responsive: true, maintainAspectRatio: false,
  771. plugins: { legend: { display: false } },
  772. scales: {
  773. y: { ticks: { callback: (v) => '$' + Math.round(v/1000) + 'k' } },
  774. x: { ticks: { autoSkip: false, maxRotation: 45 } },
  775. },
  776. },
  777. });
  778. </script>
  779. ```
  780. ### Constraints + things you must not do
  781. - **Do not invoke the `mviz` CLI for `show_widget` output.** This path renders without it. The CLI is only for standalone HTML reports.
  782. - **Do not paste mviz's own HTML into `show_widget`.** mviz emits its own styled fragments — they will not match the chat host and the bytes are wasted.
  783. - No `<!DOCTYPE>`, `<html>`, `<head>`, or `<body>` in the widget — `show_widget` rejects documents.
  784. - No `position: fixed`. It collapses the iframe's auto-sized viewport.
  785. - Only load from the allowlist: `cdnjs.cloudflare.com`, `esm.sh`, `cdn.jsdelivr.net`, `unpkg.com`, `fonts.googleapis.com`, `fonts.gstatic.com`. Chart.js from `cdnjs.cloudflare.com` is the canonical source.
  786. - Tables with more than ~3 columns or any prose-y content: render as markdown in your response text instead of inside the widget. The `visualize:read_me` design guide is explicit about this.
  787. ### Falling back to the CLI renderer
  788. When the inline renderer isn't a fit, the spec is still useful — pipe it through the CLI:
  789. - **Chart type with no Chart.js equivalent** (sankey, heatmap, calendar, etc.) — render via the CLI, offer the file. Mention that the mviz design system kicks in for the standalone output.
  790. - **`visualize:show_widget` is not available** — render via the CLI and present as an artifact.
  791. - **User is in Claude Code** — render via the CLI, write the file path, they'll open it in a browser. No inline widget surface in the TUI.
  792. - **Visualization exceeds the inline size budget** (15+ components, dense tables with sparklines, multi-section reports) — render via the CLI. Offer inline as a follow-up if they want a smaller summary view.
  793. - **Single tiny visual** (one sparkline, one 3-cell metric) — consider hand-rolling SVG directly via `show_widget` without going through the mviz spec at all. mviz earns its keep when composing multiple components; for a one-off icon it's overkill.
  794. ## Custom Themes
  795. Load custom brand colors and fonts from a YAML file:
  796. ```bash
  797. npx -y -q mviz --theme my_theme.yaml dashboard.md -o dashboard.html
  798. ```
  799. Example theme file:
  800. ```yaml
  801. name: brand-colors
  802. extends: light
  803. colors:
  804. primary: "#1a73e8"
  805. secondary: "#ea4335"
  806. palette:
  807. - "#1a73e8"
  808. - "#ea4335"
  809. - "#fbbc04"
  810. fonts:
  811. family: "'Roboto', sans-serif"
  812. import: "https://fonts.googleapis.com/css2?family=Roboto&display=swap"
  813. ```
  814. Custom themes merge with defaults - only specify what you want to override.
  815. ## Print and PDF Support
  816. Charts are optimized for printing to PDF:
  817. - **High-Quality Rendering**: Uses SVG renderer for crisp vector graphics at any zoom level
  818. - **No Page Breaks**: CSS prevents charts and tables from being split across pages
  819. - **All Labels Visible**: Category labels always shown with 45° rotation to fit
  820. When printing dashboards to PDF, all content stays intact without being cut off mid-chart.
  821. ## JSON Formatting for Editability
  822. **Use formatted (multi-line) JSON** when data may need editing. This enables smaller, more precise edits:
  823. ````markdown
  824. ```bar size=[8,5]
  825. {
  826. "title": "Monthly Sales",
  827. "x": "month",
  828. "y": "sales",
  829. "data": [
  830. {"month": "Jan", "sales": 120},
  831. {"month": "Feb", "sales": 150},
  832. {"month": "Mar", "sales": 180}
  833. ]
  834. }
  835. ```
  836. ````
  837. **Benefits:**
  838. - Each data point on its own line enables targeted edits
  839. - Changing one value: ~30 chars vs ~200+ chars with compact JSON
  840. - Easier to review diffs in version control
  841. **When to use compact JSON:**
  842. - Very small specs (< 100 chars)
  843. - Data that won't change
  844. - Single-line values like `{"value": 1250000, "label": "Revenue"}`
  845. ## JSON Schema
  846. mviz specs can be validated using the JSON Schema at:
  847. ```
  848. https://raw.githubusercontent.com/matsonj/mviz/main/schema/mviz.schema.json
  849. ```
  850. Add `$schema` to enable editor autocomplete and validation:
  851. ```json
  852. {
  853. "$schema": "https://raw.githubusercontent.com/matsonj/mviz/main/schema/mviz.schema.json",
  854. "type": "bar",
  855. "title": "Sales",
  856. ...
  857. }
  858. ```
  859. ## Color Palette (mdsinabox theme)
  860. | Color | Hex | Use |
  861. |-------|-----|-----|
  862. | Primary Blue | `#0777b3` | Primary series |
  863. | Secondary Orange | `#bd4e35` | Secondary series, accent |
  864. | Info Blue | `#638CAD` | Tertiary, informational |
  865. | Positive Green | `#2d7a00` | Success, positive values |
  866. | Warning Amber | `#e18727` | Warnings |
  867. | Error Red | `#bc1200` | Errors, negative emphasis |
  868. See `reference/chart-types.md` for complete documentation.
  869. ## Your Role
  870. You are an analytics assistant helping a human who has decision-making context that you lack. Your job is to present data clearly and surface patterns worth investigating—not to draw conclusions or make recommendations.
  871. **Key principles:**
  872. - Use a matter-of-fact tone. State what the data shows, not what it means.
  873. - Design analysis that invites further questions, not analysis that closes them.
  874. - Surface anomalies and patterns without assuming their cause or significance.
  875. - Let the human add context and make decisions.
  876. For additional guidance on creating effective data visualizations—including Tufte-inspired principles, anti-patterns to avoid, and layout examples—see `Best_practices.md`.
  877. ## Feedback
  878. Having issues with mviz? Ask Claude to create a friction log documenting the problem, then open it as an issue at https://github.com/matsonj/mviz/issues
README.md · README · 392 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

  1. # mviz
  2. Generate beautiful static reports for ad hoc analysis. A Claude skill that turns compact JSON specs into professional HTML visualizations.
  3. ![Light Mode Dashboard](LightMode.png)
  4. ![Dark Mode Dashboard](DarkMode.png)
  5. ## Why mviz?
  6. **The highest-value analysis in any company is point-in-time, highly contextual, and not reused once the decision is made.**
  7. Traditional BI tools optimize for reusability instead of usefulness. Useful analysis, the kind that drives critical decisions, needs something more:
  8. - **Fast iteration**: Query data → visualize → refine → share
  9. - **AI-native workflow**: Works seamlessly with Claude for data exploration
  10. - **Static output**: Beautiful HTML/PDF reports, no infrastructure required
  11. - **Minimal tokens**: Compact specs instead of verbose chart code
  12. Instead of writing 50-100 lines of chart boilerplate, write a compact JSON spec that gets expanded into a full HTML artifact with ECharts.
  13. ## Quick Start
  14. ### 1. Connect Your Database
  15. Connect Claude to your data using an MCP server:
  16. - **[MotherDuck MCP](https://motherduck.com/docs/sql-reference/mcp/)** - Cloud data warehouse with DuckDB compatibility
  17. - **[Local DuckDB MCP](https://github.com/motherduckdb/mcp-server-motherduck)** - Query local `.duckdb` files, Parquet, CSV, or S3 data
  18. If you do not have a database available, you can also load CSV files directly, although the amount of data you can fit in context can be quite limiting.
  19. ### 2. Add the Skill
  20. **Claude Web or Desktop:** Download [`mviz.skill`](https://gist.github.com/matsonj/1c13b656bca20b1d2cc6260309d8eb40) and add it to your project knowledge.
  21. **Claude Code:** Run `npx skills add matsonj/mviz` or clone this repo and work from the directory.
  22. ### 3. Effective Use Tips
  23. The best analysis follows four steps:
  24. 1. **Build context** — Get the data right. Query, filter, and explore until you understand what you're looking at.
  25. 2. **Develop narrative** — What's the story? What question are you answering? What pattern matters?
  26. 3. **First pass on viz** — Create an initial visualization. Don't overthink it.
  27. 4. **Refine based on what doesn't work** — Iterate. Change chart types, adjust formatting, add context.
  28. Start by exploring your data with natural questions. Claude writes SQL queries behind the scenes and brings the results into context:
  29. > *"Show me revenue by region for Q4"*
  30. > *"What are our top 10 customers by lifetime value?"*
  31. > *"Are there any anomalies in last month's sales data?"*
  32. Once you've built up context and are ready to visualize, tell Claude to **"use mviz to report on this analysis"**. Claude generates a polished HTML report from the data you've explored.
  33. ### 4. Iterate
  34. Refine your analysis by asking follow-up questions:
  35. > *"Change that bar chart to a line chart"*
  36. > *"Drill into the APAC region—what's driving that spike?"*
  37. > *"Add a table showing the top 5 products by growth rate"*
  38. ### mviz Specific Guidance
  39. mviz uses a 16-column grid.
  40. > *"Make the bar chart wider"*
  41. > *"Show two charts side by side at size=[8,6] each"*
  42. > *"Make the KPIs smaller: size=[3,2] so 5 fit in a row"*
  43. By default, it will use `size=auto` to let mviz calculate appropriate dimensions based on your data.
  44. > [!TIP]
  45. > There are more chart types available in the library than are included in the skill.md. You can tell Claude to look at the TypeScript source for more chart types if you really need them.
  46. Each iteration builds on your existing context. When you're done, save the HTML or print to PDF.
  47. ## Supported Chart Types
  48. | Type | Description | mviz.skill |
  49. |------|-------------|:----------:|
  50. | `bar` | Vertical/horizontal, grouped, stacked | ✓ |
  51. | `line` | Single or multi-series with linear interpolation | ✓ |
  52. | `area` | Simple or stacked area charts | |
  53. | `pie` | Pie or donut charts | |
  54. | `scatter` | 2D scatter plots | ✓ |
  55. | `bubble` | Scatter with size dimension (auto-detects categorical axes) | |
  56. | `boxplot` | Statistical box plots | |
  57. | `histogram` | Distribution visualization | |
  58. | `sankey` | Flow diagrams | |
  59. | `funnel` | Conversion funnels | |
  60. | `heatmap` | 2D color matrices | |
  61. | `calendar` | GitHub-style calendar heatmaps | |
  62. | `sparkline` | Compact inline charts | |
  63. | `combo` | Combined bar + line with dual axes | |
  64. | `waterfall` | Cumulative effect charts | |
  65. | `xmr` | Statistical control charts (supports `yMin`/`yMax`) | |
  66. | `dumbbell` | Before/after comparisons with directional color-coding | |
  67. ## UI Components
  68. | Type | Description | mviz.skill |
  69. |------|-------------|:----------:|
  70. | `big_value` | Large KPI metric display | |
  71. | `delta` | Change indicator with arrow | |
  72. | `table` | Data tables with formatting and inline sparklines | ✓ |
  73. | `alert` | Colored notification banners | |
  74. | `note` | Information callout boxes | ✓ |
  75. | `text` | Styled paragraphs | |
  76. | `textarea` | Markdown-rendered text blocks | ✓ |
  77. | `empty_space` | Layout spacing component | ✓ |
  78. ## File References (JSON and CSV)
  79. Reference external files instead of embedding large JSON specs:
  80. ````markdown
  81. ```bar file=data/monthly-sales.json
  82. ```
  83. ````
  84. ### DuckDB Workflow
  85. CSV files work great for data exploration with DuckDB:
  86. ```bash
  87. # Export query results
  88. duckdb -csv -c "SELECT month, revenue FROM sales GROUP BY 1" > data/monthly.csv
  89. ```
  90. ````markdown
  91. ```bar file=data/monthly.csv
  92. {"title": "Monthly Revenue", "x": "month", "y": "revenue"}
  93. ```
  94. ````
  95. CSV provides data, inline JSON provides chart options. Auto-detects x/y from first two columns if no options given.
  96. ## Report Markdown Format
  97. ````markdown
  98. ---
  99. theme: light
  100. title: My Report
  101. ---
  102. # Page Title
  103. ## Section Name
  104. ```big_value size=[4,2]
  105. {"value": 125000, "label": "Revenue", "format": "currency0m"}
  106. ```
  107. ```delta size=[4,2]
  108. {"value": 0.15, "label": "vs Last Month", "format": "pct0"}
  109. ```
  110. ```bar size=[8,6] file=data/sales.json
  111. ```
  112. ```line size=[8,6] file=data/trend.json
  113. ```
  114. ````
  115. ### Layout Rules
  116. - `# Title` creates a new section (first one also sets page title)
  117. - `## Section` creates a subsection title (no visual divider)
  118. - `---` creates a visual section divider
  119. - `===` creates a page break for printing
  120. - `size=[cols,rows]` controls 16-column grid layout
  121. - `size=auto` auto-calculates size based on data
  122. - `file=path` references external JSON
  123. - Multiple blocks on same line = same row
  124. - Empty lines = new rows
  125. ## 16-Column Grid System
  126. | Component | Default Size | Notes |
  127. |-----------|-------------|-------|
  128. | `big_value`, `delta`, `sparkline` | [4, 2] | Fits 4 per row |
  129. | `bar`, `line`, `area`, `pie` | [8, 5] | Half width |
  130. | `scatter`, `bubble`, `combo`, `funnel` | [8, 5] | Half width |
  131. | `dumbbell` | [12, 6] | 3/4 width for comparisons |
  132. | `table`, `heatmap` | [16, 4-10] | Full width |
  133. | `xmr`, `calendar` | [16, 6] | Full width, tall |
  134. ## Table with Sparklines
  135. Tables support inline sparkline columns for trend visualization:
  136. ```json
  137. {
  138. "type": "table",
  139. "columns": [
  140. {"id": "product", "title": "Product"},
  141. {"id": "sales", "title": "Sales", "fmt": "currency"},
  142. {"id": "trend", "title": "Trend", "type": "sparkline", "sparkType": "line"},
  143. {"id": "progress", "title": "Goal", "type": "sparkline", "sparkType": "pct_bar", "width": 100}
  144. ],
  145. "data": [
  146. {"product": "Widget", "sales": 125000, "trend": [85, 92, 88, 95, 102, 110, 125], "progress": 0.85}
  147. ]
  148. }
  149. ```
  150. Sparkline types: `line`, `bar`, `area`, `pct_bar` (progress bar), `dumbbell` (before/after)
  151. ## Format Options
  152. | Format | Output | Description |
  153. |--------|--------|-------------|
  154. | `auto` | 1.000m, 10.00k | **Smart auto-format (default)** |
  155. | `currency_auto` | $1.000m, $10.00k | Smart auto-format with currency symbol |
  156. | `currency0m` | $1.2m | Millions |
  157. | `currency0k` | $125k | Compact thousands |
  158. | `currency` | $1,250,000 | Full currency |
  159. | `pct0` | 15% | Percentage integer |
  160. | `pct` | 15.0% | Percentage with decimal |
  161. | `pct1` | 15.0% | Percentage with 1 decimal |
  162. | `num0` | 1,250 | Number with commas |
  163. Smart formatting automatically picks the right suffix (k, m, b) based on magnitude and shows 4 significant digits. Negative values display in parentheses: `(1.000m)`.
  164. ### Auto-Detected Formatting
  165. Chart axes automatically detect the appropriate format based on field names:
  166. | Field Pattern | Auto Format | Example |
  167. |---------------|-------------|---------|
  168. | revenue, sales, price, cost, profit | `currency_auto` | $1.250m |
  169. | pct, percent, rate, ratio | `pct` or `pct0` | 15.0% |
  170. | All other fields | `auto` | 1.250m |
  171. Override with an explicit `format` field in the chart spec.
  172. ## Theme Toggle
  173. Reports include a theme toggle button (top right) that switches between light and dark modes. All charts dynamically update when the theme changes.
  174. Set the default theme in frontmatter:
  175. ```yaml
  176. ---
  177. theme: dark
  178. title: My Report
  179. ---
  180. ```
  181. ## Print and PDF Support
  182. Charts are optimized for printing to PDF:
  183. - **High-Quality Rendering**: Uses SVG renderer for crisp vector graphics at any zoom level
  184. - **No Page Breaks in Charts**: CSS prevents charts and tables from being split across pages
  185. - **All Labels Visible**: Category labels are always shown (with 45° rotation to fit)
  186. When printing reports to PDF, all content stays intact without visual elements being cut off.
  187. ## Visual Style (mdsinabox theme)
  188. Clean, data-focused styling:
  189. - **Font**: Helvetica Neue (system sans-serif)
  190. - **Signature**: Orange accent line at top of reports
  191. - **Background**: Paper (`#f8f8f8`) for light, dark (`#231f20`) for dark
  192. ### Color Palette
  193. | Color | Hex | Use |
  194. |-------|-----|-----|
  195. | Primary Blue | `#0777b3` | Primary series |
  196. | Secondary Orange | `#bd4e35` | Secondary series, accent |
  197. | Info Blue | `#638CAD` | Tertiary |
  198. | Positive Green | `#2d7a00` | Success, positive values |
  199. | Warning Amber | `#e18727` | Warnings |
  200. | Error Red | `#bc1200` | Errors, negative emphasis |
  201. ## Project Structure
  202. ```
  203. chart-skill/
  204. ├── ts-src/ # TypeScript implementation
  205. │ ├── cli.ts # CLI entry point
  206. │ ├── index.ts # Library exports
  207. │ ├── types.ts # TypeScript type definitions
  208. │ ├── core/ # Shared utilities
  209. │ │ ├── themes.ts # Colors, palettes, theme config
  210. │ │ ├── formatting.ts # Number formatting
  211. │ │ └── css.ts # CSS generation
  212. │ ├── charts/ # 17 chart type modules
  213. │ │ ├── bar.ts, line.ts, area.ts, pie.ts, scatter.ts, bubble.ts
  214. │ │ ├── boxplot.ts, histogram.ts, waterfall.ts, xmr.ts
  215. │ │ ├── sankey.ts, funnel.ts, heatmap.ts, calendar.ts
  216. │ │ └── sparkline.ts, combo.ts, dumbbell.ts
  217. │ ├── components/ # 8 UI component modules
  218. │ │ ├── big_value.ts, delta.ts, alert.ts, note.ts
  219. │ │ ├── text.ts, textarea.ts, empty_space.ts, table.ts
  220. │ └── layout/ # Report parser
  221. │ ├── parser.ts # Markdown layout parsing
  222. │ └── templates.ts # HTML templates
  223. ├── build_skill.py # Builds .skill package for distribution
  224. ├── tests/
  225. │ ├── harness/ # Visual test harness markdown
  226. │ ├── dashboard-inline/ # Test dashboard with inline JSON
  227. │ └── dashboard-with-refs/ # Test dashboard with file references
  228. ├── docs/
  229. │ ├── MD-CHARTS-PROJECT.md # Original project specification
  230. │ └── agents.md # Skill authoring reference
  231. └── skill-bundle/ # Source files for the skill
  232. ├── SKILL.md # Skill instructions (with YAML frontmatter)
  233. ├── reference/
  234. │ └── chart-types.md # Complete API reference
  235. └── examples/ # JSON and markdown examples
  236. ```
  237. ## Warning Messages
  238. The chart generator outputs helpful warnings to stderr when issues are detected:
  239. | Warning | Cause | Solution |
  240. |---------|-------|----------|
  241. | `Invalid JSON in 'bar' block` | Malformed JSON syntax | Check JSON syntax, ensure proper quoting |
  242. | `Unknown component type 'bars'` | Typo in chart type | Use suggested type (e.g., `bar` not `bars`) |
  243. | `Cannot resolve 'file=...'` | File reference without base directory | Use file path argument or inline JSON |
  244. | `Row exceeds 16 columns` | Too many components in one row | Reduce component widths or split into rows |
  245. | `Invalid value for 'value' in big_value` | Wrong data type (e.g., string instead of number) | Ensure values match expected types |
  246. Warnings include context like content previews, suggestions for similar types, and section/row information to help locate issues.
  247. ## CLI Options
  248. ```bash
  249. npx mviz dashboard.md -o output.html # Generate HTML (requires -o flag)
  250. npx mviz --lint dashboard.md # Validate only (no output)
  251. npx mviz -l spec.json # Short form of --lint
  252. ```
  253. The `-o` flag is required and specifies the output file. The `--lint` flag validates your spec without generating HTML output. Useful for CI/CD pipelines or quick validation.
  254. ## Running Tests
  255. ```bash
  256. cd ts-src
  257. npm test # TypeScript tests (vitest)
  258. npm run build # Build TypeScript
  259. npm run typecheck # Type checking only
  260. ```
  261. ## Skill Bundle
  262. The skill bundle (`skill-bundle-compact/`) is optimized for Claude for Web with minimal token usage (~750 tokens). Supports essential types:
  263. - **Charts:** bar, line, scatter
  264. - **Components:** table (with sparklines), note, textarea, empty_space
  265. For additional chart types (pie, area, heatmap, sankey, etc.), Claude can reference the TypeScript source code in this repository. See `Best_practices.md` for layout guidance and visualization principles.
  266. ## Using with Claude
  267. ### Claude Code (CLI)
  268. The skill is automatically available when working in this project directory.
  269. ### Claude Web (claude.ai)
  270. 1. Create a new Claude project
  271. 2. Upload the `.skill` file or all files from `skill-bundle/` to the project knowledge base
  272. 3. Claude will have access to the skill, examples, and generator
  273. ## Dependencies
  274. - Node.js 24.12+
  275. ## Design Philosophy
  276. Data visualization best practices:
  277. - Maximize data-ink ratio (minimal non-data elements)
  278. - Tight, dense layouts for reports
  279. - No gratuitous animations or visual clutter
  280. - Clean, minimal axes (no domain lines, subtle grid)
  281. - Linear interpolation for accurate data representation
  282. - Focus on data clarity over decoration
  283. ## License
  284. MIT

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.