Skip to content
◀ Blog

How to generate charts with an LLM

Have the model write a compact JSON chart spec, validate it against your real data, and send field-level errors back so it can fix the chart in one retry.

Riley Hilliard8 min read

agentscharts

The most reliable way to generate charts with an LLM is to have the model write a declarative JSON spec instead of plotting code, check that spec against the actual data before rendering, and hand any errors back to the model with the field path and a suggested fix. Most bad charts from a model come from one of two mistakes: a field name that doesn’t exist in the data, or a date treated as a category. Both are cheap to catch before anything is drawn, and a model fixes them reliably when the error says exactly what’s wrong.

How do you get an LLM to make a chart?

You give the model three things: the question, the data (or its columns and a sample of rows), and a target format to write in. The model picks the chart type, decides which column goes on which axis, and writes a title. Your code turns its output into a picture. The target format decides how often that works, because it sets how much the model has to get right in one pass and what happens when it gets something wrong.

Should the model write plotting code or a spec?

A spec, for most applications.

Plotting code (matplotlib, Plotly, D3) is what models know best, because there is a lot of it in their training data. To use it you have to execute code the model wrote, which means a sandbox with the plotting library installed, a timeout, and a way to collect the image. When the code throws, you get a stack trace you can feed back. When it runs but plots the wrong column, or silently drops rows that failed to parse, you get a plausible-looking image and no error at all. The output is also a picture, so you can’t restyle it, make it responsive, or update it with new data without asking the model again.

A declarative spec such as Vega-Lite is data instead of code. Nothing executes, the same spec renders anywhere the library runs, and you can store it, diff it and edit it. Vega-Lite is the best-known option and models write it well. The weak point is validation. Vega-Lite publishes a JSON Schema, and a schema can tell you that encoding.y.field is a string. It can’t tell you that the string names a column your data doesn’t have, because the schema never sees your data. That typo passes validation and produces an empty or wrong chart.

Plotting code General declarative spec Compact spec validated against data
Needs a sandbox Yes No No
Output An image A spec A spec
Catches a misspelled column Only if the code throws No Yes, before rendering
Error the model can act on A stack trace Schema errors about shape Path, message and suggested fix

What should a chart spec look like for an LLM?

Small enough that the model can write it in one pass, with names that read like what they do.

OpenChart, the charting library we build (and the one this site renders to static SVG at build time), uses a spec modeled on Vega-Lite’s grammar: a mark, the data rows, and an encoding that maps fields to channels. This is a complete line chart:

{
  "mark": "line",
  "data": [
    { "month": "2026-01", "revenue": 120 },
    { "month": "2026-02", "revenue": 135 }
  ],
  "encoding": {
    "x": { "field": "month", "type": "temporal" },
    "y": { "field": "revenue", "type": "quantitative" }
  }
}

Axes, scales, label placement, responsive layout and dark mode are handled by the engine, so the model doesn’t write them. Titles and the source line go in an optional chrome object (title, subtitle, source). The chart spec covers 19 marks, including bar, line, area, point, arc (pie and donut), lollipop, beeswarm, histogram, waffle and calendar, and the same family has separate spec types for tables, Sankey diagrams, network graphs and maps.

OpenChart publishes JSON Schemas generated from its TypeScript types, under @opendata-ai/openchart-core/schema. chart.schema.json covers just chart specs and is the one to hand a model as a tool’s input schema. The repo’s generating specs guide covers wiring it up with tool use, plus the transform needed for providers’ strict structured-output modes. For model context there is an llms.txt generated from the library types, and a Claude Code skill (/plugin install openchart@openchart from the tryopendata/skills marketplace) that covers the spec grammar and chart design rules.

How does validation help the model fix its own chart?

It turns a silent failure into a specific instruction. OpenChart’s validateSpec checks the spec against the data it carries and returns an error for each problem, with a code, a JSON Pointer path to the offending field, a message and a suggestion.

Here is what OpenChart’s engine returns for the chart above with revenue misspelled as reveune in the y encoding:

{
  "message": "Spec error: encoding.y.field \"reveune\" does not exist in data. Available columns: month, revenue",
  "path": "/encoding/y/field",
  "code": "DATA_FIELD_MISSING",
  "suggestion": "Use one of the available data columns: month, revenue. Did you mean \"revenue\"?"
}

The “did you mean” hint comes from edit distance against the real columns, and it’s left out when nothing is close, so the model isn’t steered toward a wrong guess. Type mistakes get the same treatment. Setting the line chart’s x to nominal returns:

{
  "message": "Spec error: encoding.x for line chart does not accept type \"nominal\". Allowed types: temporal, ordinal",
  "path": "/encoding/x/type",
  "code": "ENCODING_MISMATCH",
  "suggestion": "Change encoding.x.type to one of: temporal, ordinal"
}

That’s enough for a short repair loop. Attach your data to the model’s spec, validate, and if it fails, send the errors back as the next turn:

import { validateSpec } from "@opendata-ai/openchart-engine";

const { valid, errors } = validateSpec({ ...spec, data: rows });
if (!valid) {
  const repair = errors
    .map((e) => `${e.path}: ${e.message} ${e.suggestion}`)
    .join("\n");
  // Send `repair` back to the model, then validate its new spec.
}

Attach the data yourself rather than asking the model to copy it into the spec. It saves tokens, and the model can’t alter a number on the way through. Cap the loop at two attempts or so. OpenChart’s docs report that a single repair round closes most remaining failures, and the cap means a request the data can’t support fails fast instead of looping.

How do you render the chart once you have a spec?

Pass the validated spec to a renderer. OpenChart’s engine is headless, and there are wrappers for React (@opendata-ai/openchart-react), Vue 3, Svelte 5 and plain JavaScript, so the same spec renders in any of them without changes. In React it’s <Chart spec={spec} />, and in vanilla JavaScript it’s createChart(container, spec).

OpenChart / plot console
LOCALREADY

Change the view. The chart and its spec stay in step.

LINE / INDIVIDUAL SERIES

Jul 2026Oct 2026Week05001k1.5k2k2.5k3kTotal commitsOpenData3.3kOpenChart1.1kStatGlass1.2kStacks1.4krr74Decks847foreman346OpenStudio1k

Compare individual products: commits to date.

Inspect chart spec

The rendering configuration, with data rows omitted for readability.

{
  "mark": {
    "type": "line",
    "interpolate": "linear"
  },
  "data": "[208 rows omitted]",
  "encoding": {
    "x": {
      "field": "week",
      "type": "temporal",
      "axis": {
        "title": "Week"
      }
    },
    "y": {
      "field": "commits",
      "type": "quantitative",
      "axis": {
        "title": "Total commits"
      },
      "scale": {
        "zero": false
      }
    },
    "color": {
      "field": "product",
      "type": "nominal",
      "scale": {
        "domain": [
          "OpenChart",
          "OpenData",
          "Stacks",
          "StatGlass",
          "rr"
        ],
        "range": [
          "#ff2e88",
          "#2de2e6",
          "#a395d6",
          "#a04dff",
          "#d2c7f4"
        ]
      }
    }
  },
  "endpointLabels": true,
  "a11y": {
    "description": "Compare individual products: commits to date."
  }
}
Fig. 1 The same commit history in four views, each rendered by OpenChart at build time. Source: git history of our product repositories

On a server or in a build step, renderStaticSVG from @opendata-ai/openchart-vanilla/static returns an SVG string with no browser or DOM shim. It supports chart, layer, bar list, tile map and geographic map specs (tables, Sankey diagrams and graphs need the browser renderers). That suits agents that produce reports, or tools whose output is a file instead of a page. OpenData, our MCP server for public data, uses OpenChart to draw the charts it returns to Claude and ChatGPT.

How do you check the chart is right?

Validation only proves the chart can be drawn. It can’t tell you whether the chart answers the question.

Read the numbers before the picture. If the model aggregated anything, run the same aggregation yourself (in SQL, or a few lines of code) and compare totals. A sum over the wrong grouping makes a clean chart with wrong numbers. Better still, do the math before the chart step and give the model rows that are already aggregated, so its job is only the encoding.

Check the encoding types against what the data means: dates should be temporal and categories nominal. A year stored as a number passes as quantitative on a bar chart and plots on a continuous axis, which is valid and usually not what you wanted. A line chart rejects it, since its x axis only accepts temporal or ordinal.

Ask the model for a title that states the finding (“Revenue rose 12.5% in February”) instead of a label (“Revenue by month”), then check that finding against the data. A wrong title on a correct chart misleads readers more than a missing one.

Then look at the render. If the model can see images, render the spec and show it the result. Overlapping labels, a pie with a dozen slices and a nearly empty plot are easy to spot in a picture and hard to catch in JSON. OpenChart’s agent patterns doc ends with a spec quality rubric covering these checks. Put it in the prompt and the model can review its own spec against it.