AI: chart this

Open the Chart panel, press the AI button, and describe the chart in words - the model reads the grid's column schema and returns a ChartSpec the built-in panel renders. Ships with a deterministic mock provider; swap in your own via setAIProvider.

A live, editable Svelte 5 data grid example from the SvGrid gallery (Charts). See the SvGrid documentation for the full API.

About this example

Describing a chart in words to the Svelte 5 data grid. After enableAiCharting(api) the built-in chart panel gains an AI button: type revenue by country, stacked by product, and the model reads the grid's column schema and returns a chart config with type, group-by, split-by, measure and aggregate that the panel applies live. It ships with the deterministic mockAIProvider so no key is needed, setAIProvider plugs in a real model, and the AI helpers are free in @svgrid/grid.

The built-in chart panel gains an AI button once you call enableAiCharting(api): type a request in plain English - "revenue by country, stacked by product" - and the model turns it into a chart config (type, group-by, split-by, measure, aggregate) that's applied live. Wired to the bundled mockAIProvider so it runs with no API key; swap in setAIProvider(yourAdapter) for a real model. The AI helpers are built-in and free (MIT) in @svgrid/grid - no license needed.

Imports, features and API used

Imports: @svgrid/grid, ../shared/seed

Columns: country (Country), product (Product), company (Company), quantity (Qty), price (Price), revenue (Revenue)

Frequently asked questions

What does the model see?

The column schema, names and data types, plus the request text. It returns a chart config, not data, so nothing in the grid leaves the browser beyond the schema you already have.

How do I connect a real model?

Call setAIProvider with a function that posts the prompt to your endpoint and returns the response text; the mock provider has the same shape and is what the demo uses.

Can I edit the result?

Yes. The returned config lands in the panel's pickers, so any part of it can be adjusted by hand afterwards.

Related documentation

Source code (357-ai-chart-this.svelte)

<script lang="ts">
  /**
   * 357. AI "chart this"
   * --------------------
   * The built-in chart panel gains an AI button once you call `enableAiCharting(api)`:
   * type a request in plain English - "revenue by country, stacked by product" -
   * and the model turns it into a chart config (type, group-by, split-by, measure,
   * aggregate) that's applied live. Wired to the bundled `mockAIProvider` so it
   * runs with no API key; swap in `setAIProvider(yourAdapter)` for a real model.
   * The AI helpers are built-in and free (MIT) in @svgrid/grid - no license needed.
   */
  import {
    SvGrid,
    tableFeatures,
    setAIProvider,
    mockAIProvider,
    enableAiCharting,
    type GridColumns,
    type SvGridApi,
  } from '@svgrid/grid'
  import { makeOrders } from '../shared/seed'

  setAIProvider(mockAIProvider) // deterministic canned model for the demo

  // Project to just the chartable fields so the AI's column schema (built from
  // the row data) matches the grid's columns - no stray id / date fields.
  type Sale = { country: string; product: string; company: string; quantity: number; price: number; revenue: number }
  const features = tableFeatures({})
  let rows = $state<Sale[]>(
    makeOrders(200).map((o) => ({
      country: o.country,
      product: o.product,
      company: o.company,
      quantity: o.quantity,
      price: o.price,
      revenue: Math.round(o.quantity * o.price),
    })),
  )

  const money = { type: 'currency', currency: 'USD', options: { maximumFractionDigits: 0 } } as const
  const columns: GridColumns<Sale> = [
    { field: 'country', header: 'Country', width: 120 },
    { field: 'product', header: 'Product', width: 150 },
    { field: 'company', header: 'Company', width: 150 },
    { field: 'quantity', header: 'Qty', width: 80, align: 'right', cellDataType: 'number', format: { type: 'number', options: { maximumFractionDigits: 0 } } },
    { field: 'price', header: 'Price', width: 110, align: 'right', cellDataType: 'number', format: money },
    { field: 'revenue', header: 'Revenue', width: 130, align: 'right', cellDataType: 'number', format: money },
  ]

  // enableAiCharting wires the chart panel's AI button to aiChart() - a built-in,
  // free @svgrid/grid feature; no enterprise install or license needed.
  function onReady(next: SvGridApi<typeof features, Sale>) {
    enableAiCharting(next)
  }
</script>

<div class="demo-page" style="height: 620px; display: flex; flex-direction: column;">
  <p class="demo-lede">
    Open the <strong>Chart</strong> panel and press <strong>✨ AI</strong>, then describe the chart you
    want - e.g. <em>"total price by country stacked by product"</em> or <em>"average quantity by
    product as a line"</em>. The model returns a chart config and the panel draws it. Powered by the
    bundled mock provider; wire <code>setAIProvider()</code> to a real model for production.
  </p>
  <div style="flex: 1; min-height: 0;">
    <SvGrid
      columnResize
      data={rows}
      columns={columns}
      features={features}
      selectionMode="cell"
      containerHeight="100%"
      onApiReady={onReady}
      charting={{ defaultOpen: true, width: 500 }}
    />
  </div>
</div>

View this example on GitHub

More Charts examples

  • Chart a selection (context menu) - With integrated charting enabled, the right-click menu gains a Chart selected range item: select a block of cells, right-click, and the chart panel opens scoped to that range - the Excel chart-this gesture, built in. The item appears only when charting is on and is appended to the default context menu automatically.
  • Chart view of the grid - The `chart` prop turns the same <SvGrid> into a chart, driven by the grid’s filtered + sorted rows (search + sort flow through). A view of the grid like board and scheduler, but the renderer is free: the grid lazy-loads a built-in view wrapping the standalone SvChart via rowsToChartSpec. Flip Table <-> Chart (bar / line / area) over one source of truth.
  • Candlestick / OHLC - Candlestick and OHLC price marks with an ordinal date axis. ChartSeries.ohlc carries the four prices while values keeps the closes, so the CSV export, the screen-reader table and a 10-day moving average all work with no candle-specific code. Toggle the axis: a real time axis opens a gap over every weekend, an ordinal one spaces sessions evenly and still labels them by date. The strip under the plot is the chart brush: drag its window to pan, drag an edge to resize.
  • Box plot + error bars - Distribution rather than average: box plots with the 1.5 IQR whisker rule and individual outliers, next to the same data as a bar chart of the means with error bars. two regions with nearly identical means sit side by side in the bars and look nothing alike in the boxes. boxStats() summarises a raw sample, rowsToBoxSpec() does it per group, and ChartSeries.errors annotates any existing mark without changing its type.
  • Axes, titles and styling - The chart hands the decisions back: a numeric x axis that spreads payload sizes the way the numbers do, pinned domains with a fixed tick interval and a formatter per axis, grid lines on or off, a shaded budget band, a vertical reference line, per-point markers and colours, a stepped dashed series on the right axis, a title / subtitle / caption, a legend on any side, and a tooltip snippet in single-series mode. Below it, 50,000 monitoring readings decimated to one point per pixel with LTTB or min / max - toggle it off to see the cost.