GrepBoard/Manuals
605 manuals ·

Extract numbers from a chart screenshot with AI and check error

·Tested on Claude Sonnet 5.5 · 2026-10·Test scope ↓·6 steps

Extract numbers from chart screenshots and verify estimation errors caused by missing labels. The prompt records the basis of each value to check with Python.

When report slides contain only bar chart images without raw tables, reusing numbers requires manual extraction. You can ask a vision-capable language model to turn the image into a table. Bars without data labels require estimating between grid ticks, so compare what it read with the original data to see whether there is any error.

Instruct the model to provide a basis column for each number, then verify values against ground truth with a comparison script. For broader table formatting verification, see Convert pasted tables to CSV.

[1] Prepare reference chart data with known numbers. We use 6 months of visitor data (in thousands).

truth.en.csv
month,visitorsJan,42Feb,75Mar,58Apr,91May,63Jun,84

We evaluate two chart variants: a labeled version displaying numbers above bars, and an unlabeled version with only Y-axis ticks (0 to 100). In practice, attach a chart screenshot (PNG). For reproducible automated execution, SVG chart markup was passed instead. The excerpt below is abridged; the full code given to the model is in the prompt files under run/.

chart.svg
<svg width="500" height="300" viewBox="0 0 500 300">  <line x1="60" y1="240" x2="460" y2="240" stroke="#333"/>  <!-- Y ticks 0, 20, 40, 60, 80, 100 -->  <line x1="60" y1="200" x2="460" y2="200" stroke="#eee"/>  <line x1="60" y1="160" x2="460" y2="160" stroke="#eee"/>  <line x1="60" y1="120" x2="460" y2="120" stroke="#eee"/>  <line x1="60" y1="80" x2="460" y2="80" stroke="#eee"/>  <!-- Jan to Jun bars (labeled version includes text number above bar) -->  <rect x="85" y="156" width="35" height="84" fill="#3b82f6"/>  <text x="102" y="150" text-anchor="middle">42</text>  <text x="102" y="260" text-anchor="middle">Jan</text>  <!-- ... Feb to Jun omitted ... --></svg>

[2] Construct the prompt. Enclose the chart within <chart> tags and require a basis column.

text
Extract monthly visitor data from the chart into CSV format. Rules:1. Header line exactly: month,visitors,basis2. Output one row per month from Jan to Jun.3. visitors must be an integer only.4. basis indicates how the value was determined: "label" if read directly from a data label above the bar, or "estimated" if inferred from the axis ticks and grid.5. Output only the CSV data with no code fences and no extra text. <chart>{chart_image_or_code}</chart>

Following the grounding best practice from Anthropic, the model is asked to state the source of each extracted number. Whether the column reduces hallucination was not compared in this run.

[3] Execute the prompt against both chart variants.

console
$ claude -p --model claude-sonnet-5-5 --max-turns 1 --tools "" --setting-sources "" --strict-mcp-config < run/en_labeled.1.prompt.txt > run/en_labeled.1.out.txt$ cat run/en_labeled.1.out.txt
output
month,visitors,basisJan,42,labelFeb,75,labelMar,58,labelApr,91,labelMay,63,labelJun,84,label

All 6 rows in the labeled version were categorized as label with zero numeric discrepancy.

Next, execute against the unlabeled chart variant.

console
$ claude -p --model claude-sonnet-5-5 --max-turns 1 --tools "" --setting-sources "" --strict-mcp-config < run/en_unlabeled.1.prompt.txt > run/en_unlabeled.1.out.txt$ cat run/en_unlabeled.1.out.txt
output
month,visitors,basisJan,42,estimatedFeb,75,estimatedMar,58,estimatedApr,91,estimatedMay,63,estimatedJun,84,estimated

All 6 rows were flagged as estimated. A second run (en_labeled.2.out.txt and en_unlabeled.2.out.txt) yielded identical rows and classifications.

[4] Create the verification script check_chart.py. It reads the truth file and the extracted file with the standard csv module and checks the header, row count, month order and duplicate keys, and non-numeric values (including NaN). A label row must have zero error; an estimated row must stay within an error threshold (15% by default, an example value chosen for this guide). When the truth value is 0 it does not divide; the value read must be 0 to pass.

run/check_chart.py
#!/usr/bin/env python3"""usage: check_chart.py truth.csv out.csv [max_err_pct] [ko|en]"""import csv, sys MSG = {    "ko": ("정답 헤더 오류", "헤더 불일치: {h}", "행 수 불일치: {a} != {b}", "FAIL 행 {i}: 열 수 오류 -> {r}",           "FAIL 행 {i}: 형식/순서/키 오류 -> {m}, {v}, {b}", "FAIL 행 {i} [{m}]: 라벨 불일치 -> 읽은값={val}, 원본={exp}",           "WARN 행 {i} [{m}]: 추정 한도 초과 -> {p}", "OK   행 {i} [{m}]: {b} 확인 ({val})", "{k}: {n}건, 평균 절대오차={avg:.2f}",           "원본 0 대비 {d}"),    "en": ("Truth header error", "Header mismatch: {h}", "Row count mismatch: {a} != {b}", "FAIL row {i}: wrong column count -> {r}",           "FAIL row {i}: format/order/key error -> {m}, {v}, {b}", "FAIL row {i} [{m}]: label mismatch -> read={val}, truth={exp}",           "WARN row {i} [{m}]: estimate over limit -> {p}", "OK   row {i} [{m}]: {b} confirmed ({val})", "{k}: {n} rows, mean absolute error={avg:.2f}",           "{d} against a truth of 0"),}args = sys.argv[3:]lang = "en" if "en" in args else "ko"t = MSG[lang]nums = [a for a in args if a not in ("ko", "en")] truth_rows = [r for r in csv.reader(open(sys.argv[1], encoding="utf-8")) if len(r) == 2]if not truth_rows or truth_rows[0] != ["month", "visitors"]:    print(t[0]); sys.exit(2)truth = {r[0].strip(): int(r[1]) for r in truth_rows[1:] if r[1].strip().isdigit()}truth_order = [r[0].strip() for r in truth_rows[1:]] lines = [l for l in open(sys.argv[2], encoding="utf-8") if not l.startswith("```") and l.strip()]rows = [r for r in csv.reader(lines) if r]if not rows or rows[0] != ["month", "visitors", "basis"]:    print(t[1].format(h=rows[0] if rows else "empty")); sys.exit(1)if len(rows[1:]) != len(truth_order):    print(t[2].format(a=len(rows[1:]), b=len(truth_order))); sys.exit(1) max_err = float(nums[0]) if nums else 15.0seen, bad, diffs = set(), 0, {"label": [], "estimated": []} for idx, r in enumerate(rows[1:], 1):    if len(r) != 3:        print(t[3].format(i=idx, r=r)); bad += 1; continue    m, v_str, b = r[0].strip(), r[1].strip(), r[2].strip().lower()    if m in seen or m != truth_order[idx - 1] or b not in diffs or not v_str.isdigit():        print(t[4].format(i=idx, m=m, v=v_str, b=b)); bad += 1; continue    seen.add(m)    val, exp = int(v_str), truth[m]    diff = abs(val - exp)    diffs[b].append(diff)    if b == "label" and diff != 0:        print(t[5].format(i=idx, m=m, val=val, exp=exp)); bad += 1    elif b == "estimated" and (diff > 0 if exp == 0 else diff / exp * 100.0 > max_err):        p = t[9].format(d=diff) if exp == 0 else f"{diff / exp * 100:.1f}%"        print(t[6].format(i=idx, m=m, p=p)); bad += 1    else:        print(t[7].format(i=idx, b=b, m=m, val=val)) print("-" * 50)for k, v in diffs.items():    if v: print(t[8].format(k=k, n=len(v), avg=sum(v) / len(v)))sys.exit(1 if bad else 0)

[5] Run the verification. The labeled model output matches all 6 rows and exits with status 0.

console
$ python run/check_chart.py run/truth.en.csv run/en_labeled.1.out.txt enOK   row 1 [Jan]: label confirmed (42)OK   row 2 [Feb]: label confirmed (75)OK   row 3 [Mar]: label confirmed (58)OK   row 4 [Apr]: label confirmed (91)OK   row 5 [May]: label confirmed (63)OK   row 6 [Jun]: label confirmed (84)--------------------------------------------------label: 6 rows, mean absolute error=0.00

The unlabeled output also has zero error on all 6 rows. But the input in this run was SVG code, from which the values can be computed out of the bar heights (such as height="84"). The result does not test how accurately the model reads grid ticks by eye in a screenshot. To see that, feed a PNG and compare with the same script; this was not tested in this run.

console
$ python run/check_chart.py run/truth.en.csv run/en_unlabeled.1.out.txt enOK   row 1 [Jan]: estimated confirmed (42)OK   row 2 [Feb]: estimated confirmed (75)OK   row 3 [Mar]: estimated confirmed (58)OK   row 4 [Apr]: estimated confirmed (91)OK   row 5 [May]: estimated confirmed (63)OK   row 6 [Jun]: estimated confirmed (84)--------------------------------------------------estimated: 6 rows, mean absolute error=0.00

The gaps in the script were tested with hand-made input. There were 6 cases: a misread label, a duplicate key, a NaN input, an estimate over the limit (June at 110), and a pair for a month whose truth is 0 (reading 0 is a valid input, reading 3 is an error). Only the valid one passed; the 5 faulty ones all exited with status 1. The representative case reads January's label as 45 (bad_label_err.en.csv, not model output).

console
$ python run/check_chart.py run/truth.en.csv run/bad_label_err.en.csv enFAIL row 1 [Jan]: label mismatch -> read=45, truth=42OK   row 2 [Feb]: label confirmed (75)OK   row 3 [Mar]: label confirmed (58)OK   row 4 [Apr]: label confirmed (91)OK   row 5 [May]: label confirmed (63)OK   row 6 [Jun]: label confirmed (84)--------------------------------------------------label: 6 rows, mean absolute error=0.50

[6] Boundaries and limitations. Do not use grid estimation for 3D charts, perspective-distorted graphics, or pie charts lacking radial markings. If the axis uses a logarithmic scale, values read as if it were linear will not be right, so check the axis type first. When converting chart captures with vision models, check the basis column and review the rows marked estimated.

#chart#data-extraction#csv#claude