Let an LLM Generate Charts from Your DataFrame in Python

Ask a question about a DataFrame in plain English, have an LLM choose the chart, and draw it with Matplotlib. The model returns a validated JSON spec instead of code.

The safest way to let an LLM make charts from a DataFrame is to have it return a small JSON spec (chart type, columns, aggregation, title) and draw the chart with code you wrote. You send the model the column names and types, not the rows, and force it to answer through a tool call so the reply matches a schema. Then you validate the spec against the DataFrame and render it. The alternative, asking for Matplotlib code and calling exec() on it, is shorter but runs arbitrary code, so the second half of this post covers when that is acceptable.

The charts below are drawn from example specs I wrote to match the schema, so they show the rendering half exactly but not a live model's choices. The API call follows the SDK's documented signature (anthropic 2.14.0), but I haven't run it against the live service, and what a model returns will vary.

Quick Example

This part runs offline. It builds 600 simulated orders, defines the schema the model has to fill in, validates a spec, and draws it:

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

rng = np.random.default_rng(31)
n = 600
df = pd.DataFrame({
    "order_date": pd.to_datetime("2025-01-01") + pd.to_timedelta(rng.integers(0, 365, n), unit="D"),
    "region": rng.choice(["North", "South", "East", "West"], n, p=[0.2, 0.25, 0.3, 0.25]),
    "category": rng.choice(["Laptops", "Monitors", "Accessories"], n, p=[0.25, 0.3, 0.45]),
    "units": rng.integers(1, 9, n),
})
unit_price = df["category"].map({"Laptops": 900, "Monitors": 260, "Accessories": 35})
df["revenue"] = (df["units"] * unit_price * rng.normal(1, 0.08, n)).round(2)
df["month"] = df["order_date"].dt.to_period("M").dt.to_timestamp()

CHART_TOOL = {
    "name": "make_chart",
    "description": "Describe one chart that answers the user's question about the DataFrame.",
    "input_schema": {
        "type": "object",
        "properties": {
            "chart_type": {"type": "string", "enum": ["bar", "line", "scatter", "histogram"]},
            "x": {"type": "string", "description": "Column for the x-axis"},
            "y": {"type": ["string", "null"], "description": "Column for the y-axis (null for histogram)"},
            "color": {"type": ["string", "null"], "description": "Optional column to split into colored groups"},
            "agg": {"type": "string", "enum": ["sum", "mean", "count", "none"]},
            "title": {"type": "string"},
        },
        "required": ["chart_type", "x", "agg", "title"],
    },
}


def validate_spec(df, spec):
    """Reject anything that isn't a real column or an allowed value."""
    allowed = CHART_TOOL["input_schema"]["properties"]
    if spec["chart_type"] not in allowed["chart_type"]["enum"]:
        raise ValueError(f"Unsupported chart type: {spec['chart_type']}")
    if spec["agg"] not in allowed["agg"]["enum"]:
        raise ValueError(f"Unsupported aggregation: {spec['agg']}")
    for key in ("x", "y", "color"):
        if spec.get(key) and spec[key] not in df.columns:
            raise ValueError(f"Column not in DataFrame: {spec[key]!r}")


PALETTE = ["#5f3dc4", "#e8590c", "#0b7285", "#c2255c"]


def draw_chart(df, spec):
    validate_spec(df, spec)
    x, y, color, agg = spec["x"], spec.get("y"), spec.get("color"), spec["agg"]
    fig, ax = plt.subplots(figsize=(8, 4.6))
    kind = spec["chart_type"]

    if kind == "histogram":
        ax.hist(df[x], bins=20, color=PALETTE[0])
        ax.set_ylabel("Orders")
    elif kind == "scatter":
        for c, (name, g) in zip(PALETTE, df.groupby(color) if color else [(None, df)]):
            ax.scatter(g[x], g[y], s=22, alpha=0.7, color=c, label=name)
        ax.set_ylabel(y)
    else:
        keys = [x] + ([color] if color else [])
        data = df.groupby(keys)[y].agg(agg).reset_index()
        if kind == "bar":
            data = data.sort_values(y, ascending=False)
            ax.bar(data[x], data[y], color=PALETTE[0])
        else:
            for c, (name, g) in zip(PALETTE, data.groupby(color) if color else [(None, data)]):
                ax.plot(g[x], g[y], marker="o", color=c, label=name)
        ax.set_ylabel(f"{agg} of {y}")
    ax.set_xlabel(x)
    ax.set_title(spec["title"])
    ax.spines[["top", "right"]].set_visible(False)
    if color:
        ax.legend(frameon=False, title=color)
    fig.tight_layout()
    return fig


spec = {"chart_type": "bar", "x": "region", "y": "revenue", "color": None,
        "agg": "sum", "title": "Total revenue by region"}
draw_chart(df, spec)
plt.show()

Bar chart of total revenue by region, East highest and North lowest

East has the highest revenue (about $245K) and North the lowest (about $145K). The model's only job is producing spec. The next section does that with the Anthropic API:

import anthropic

client = anthropic.Anthropic()  # reads ANTHROPIC_API_KEY from the environment


def ask_for_spec(df, question):
    schema = "\n".join(f"- {col}: {dtype}" for col, dtype in df.dtypes.astype(str).items())
    response = client.messages.create(
        model="claude-sonnet-5-5",
        max_tokens=500,
        system="You turn questions about a pandas DataFrame into a chart spec. "
               "Only use the columns listed. Call make_chart exactly once.",
        tools=[CHART_TOOL],
        tool_choice={"type": "tool", "name": "make_chart"},
        messages=[{"role": "user", "content": f"Columns:\n{schema}\n\nQuestion: {question}"}],
    )
    return next(block.input for block in response.content if block.type == "tool_use")


spec = ask_for_spec(df, "Which region brings in the most revenue?")
draw_chart(df, spec)
plt.show()

Why Return a Spec Instead of Code?

Both approaches turn a question into a chart. They differ in what you have to trust:

JSON spec (tool use) Generated Matplotlib code
What the model returns Chart type, columns, aggregation A Python script
What runs on your machine Your own draw_chart Whatever the model wrote
Failure mode A rejected spec An exception, or code you didn't expect
Flexibility Only the chart types you support Anything Matplotlib can do
Consistent styling Yes, set once in draw_chart Varies per answer

tool_choice={"type": "tool", "name": "make_chart"} forces the model to call that tool, so the response always contains a tool_use block whose input follows your input_schema. Treat that as a strong guide rather than a guarantee. Validation is still your job, which is what validate_spec is for.

Send the Schema, Not the Data

The prompt includes only column names and dtypes. That is enough for the model to choose columns, and it keeps customer rows out of the request. If a column's meaning isn't obvious from its name, add a one-line description per column. For categorical columns, listing a few example values (region: North, South, East, West) helps the model filter correctly.

More Questions, More Charts

The same draw_chart handles other questions. Here is what a model would plausibly return for two more, drawn from the same DataFrame:

line_spec = {"chart_type": "line", "x": "month", "y": "revenue", "color": "category",
             "agg": "sum", "title": "Monthly revenue by category"}
draw_chart(df, line_spec)
plt.show()

Line chart of monthly revenue for Accessories, Laptops and Monitors during 2025, with Laptops highest and spiking in January and August

Laptops dominate (about $556K for the year against $200K for monitors and $47K for accessories), and the laptop line is spiky, with its highest months in January and August.

scatter_spec = {"chart_type": "scatter", "x": "units", "y": "revenue", "color": "category",
                "agg": "none", "title": "Revenue vs units per order"}
draw_chart(df, scatter_spec)
plt.show()

Scatter chart of revenue against units per order, with three separate rising bands for Laptops, Monitors and Accessories

The scatter forms three bands, one per category, because each category has a fixed unit price.

What Happens When the Model Gets It Wrong?

Models sometimes invent a column. Validation turns that into a clear error you can show the user or send back to the model for a retry:

try:
    draw_chart(df, {"chart_type": "bar", "x": "region", "y": "profit", "agg": "sum", "title": "Profit"})
except ValueError as e:
    print(e)
Column not in DataFrame: 'profit'

A simple retry loop appends the error message to the conversation and asks for a corrected spec, usually once or twice at most. Also check that the chart makes sense: agg="sum" on a column like unit_price is allowed by the schema but meaningless.

When Is Generated Code Acceptable?

Asking for Matplotlib code is fine for a personal notebook where you read the code before running it, or when you run it in a sandbox with no network or file access. Don't exec() model output inside a web app that handles other people's questions or data. If you go that way, show the code, keep it to a single plotting function, and run it in an isolated process.

Practical Tips

  • Cap the chart menu. Four chart types you've styled well beat twenty the model can combine badly.
  • Log the spec. Saving the question and spec lets you see which questions fail and add support for them.
  • Use a small, fast model for this. Choosing columns from a schema is an easy task, and latency matters in an interactive app.
  • Add an "unsupported" path. Let the model say a question can't be answered with the data, or you'll get a chart that answers a different one.

Similar Topics