Document, Diagram, and Interface Understanding › Tables, Charts, and Diagrams
Language AI HandbookAll chapters Tables convey more than a rectangle of cells
In a ruled table, summing ink over each axis can highlight horizontal and vertical lines. A full-length line produces a strong projection signal, while a short segment from a merged cell may produce a weaker or partial signal. Projection profiles can be dominated by text strokes, heavy shading or border decorations. The common hypothesis that strong lines correspond to grid boundaries needs an explicit validation step. With a borderless table, aligned text can supply evidence for columns. A wrapped label can shift its second line far enough to be near another column boundary, and several centered numeric values can have different widths. A typed reference grid helps distinguish failures in discovering the grid from failures in assigning content to it.
When the purpose is question answering, evaluate which header governs the returned cell. A table can use a multi-row header to express both “forecast” and “Q2.” A cell under “Actual” at the same coordinates in another template may have the same number but answer a different question. This is an example where correct text and the immediate row and column indices may be insufficient unless they are tied to structural roles. For a reported value, retain the header path and evidence region when that detail matters to the user.
A table schema also governs absent cells and repeated identifiers. An empty numeric field, a displayed dash and a missing row mean different things to a downstream consumer. Treat format coercion as a separate operation after structure has been evaluated. A parser that fills a missing amount with zero might produce a sum but lose the ability to indicate incomplete evidence. If a legitimate blank is intended, record that interpretation using the evaluation contract rather than silently treating every absent string the same way.
A related check concerns normalization across cells. A task may accept commas as thousands separators, require preserving a currency code or evaluate whether units are converted correctly. A sorted list of values without their units can match a reference numerically and still be meaningless if the values use different measures. The invoice keeps its schema deliberately simple, so the known corrupted character forces rejection rather than recovery by a locale rule. A deployment evaluation can declare acceptable spellings, return the source text alongside the parsed value and verify that normalization does not turn distinct quantities into the same value.
A layout model can assign types such as caption, heading, body text or table. These labels can guide reading order and grouping, but a label alone does not encode which caption belongs with which figure. DocLayNet includes 11 human-annotated layout classes. LayoutLMv3 combines text and visual input and pretrains with unified masking objectives. A system that consumes OCR tokens and locations can retain those tokens as inspectable intermediate outputs. A system such as Donut can generate a labeled document representation directly from the image without using a separate OCR engine. That architecture can still produce evidence regions if it is designed and measured to do so.
The simple table below uses three declared column centers and three row centers. A fixture box is assigned to the nearest row and column. The gate on its vertical center excludes the header and totals. Nearest-center assignment is a transparent baseline with known geometry. It does not discover grids, spanning cells or line breaks. A collision is returned separately rather than treated as another correct cell. In a production comparison, compute row and column structure scores independently of text recognition.
PythonIn [13]Expand
def table_cells(
boxes, column_centers=(98, 363, 520), row_centers=(159, 204, 249)
):
candidates = {}
collisions = []
for box in boxes:
x, y = box.center
if not 125 <= y <= 270:
continue
row = int(np.argmin(np.abs(np.asarray(row_centers) - y)))
col = int(np.argmin(np.abs(np.asarray(column_centers) - x)))
key = (row, col)
if key in candidates:
collisions.append(key)
else:
candidates[key] = box
return candidates, collisions
def parse_money(box):
value = box.value
whole, dot, minor = value.partition(".")
if not (
whole.isascii()
and whole.isdecimal()
and dot
and minor.isascii()
and minor.isdecimal()
and len(minor) == 2
):
return None
return Decimal(value)
truth_cells, _ = table_cells(boxes)
result_cells, collisions = table_cells(proposed)
amounts = [parse_money(result_cells[i, 2]) for i in range(3)]
subtotal_box = next(box for box in proposed if box.key == "subtotal")
total_box = next(box for box in proposed if box.key == "total")ConsoleOut [14]Expand
Structurally assigned cells: 9; collisions: 0
Exact cell strings: 8/9
Parsed line-item amounts: [Decimal('120.00'), None, Decimal('32.10')]
Printed subtotal: 227.60 (470, 300, 542, 315)
Printed amount due: 273.12 (470, 384, 542, 399)
Line-item reconciliation possible: FalseAll nine table cells are present, yet only eight have the correct string. The printed subtotal and total remain separately readable. A system can return a value sourced from the printed total while declining to claim that it verified the line-item calculation. If checkable values reconcile, a separate numerical rule can compare the exact decimal subtotal plus tax with the printed total. It cannot safely assume a malformed cell is a zero or silently substitute a nearby amount. The lesson applies to inputs with units or currency marks as well: decide the schema before coercing values.
Checking calibration assumptions before comparing bars
An image reader measures positions in pixels. The chart author presents values on an axis that may use a different origin, unit and scale. To turn a pixel into a number, attach tick labels to their pixel locations and fit the appropriate calibration. In the synthetic raster the axis is linear; the larger the value, the smaller the pixel row because the image origin is at the top. For an axis with a logarithmic scale, equal pixel spacings have a different interpretation. The assumptions about scale and axis direction belong in the numerical report and should be checked independently of bar localization.
A difference in the recovered height can originate in the location of the top edge, the inferred scale and offset, the mapping of a bar to a category, or the read unit. If a quarter label is attached to the wrong bar, calibration can recover an excellent number for the wrong quarter. A useful extraction record includes candidate label, raw pixel coordinate, associated axis and calibrated number. A benchmark can then compare matching categories first and include unit consistency in the final value check. Ranking bars can be robust to some additive calibration changes when all bars use the same scale, while recovering an exact value is directly sensitive to those changes.
Two reference ticks determine a straight line when their pixel rows differ. Additional ticks permit a residual check, which can expose an incompatible observation but cannot always identify which label or coordinate caused it. A very small residual on an overfitted calibration is no substitute for confirming the assigned labels. When fitting a line, compare the fitted tick values with their declared references and inspect large residuals. A disagreement might indicate a badly read label, a wrong tick pixel or a bad choice of axis model. The companion fixture below changes one assigned label in isolation so that these sources remain distinguishable.
With a thick or antialiased mark there may be several plausible pixel rows for the top. The current raster uses an exact selected color in a simple rectangular region. It contains no overlapping bars, gradient fill, grid lines of the same mark color or thick outlines around the bar. A parser deployed on exported charts needs a declared mark detector for such cases. Testing under image rescaling is also useful because interpolation can change the available color values. In this fixture the exact-color detector runs on the original pixel grid, and the separate display rendering does not change the numbers read from that grid.
The pure localization error discussed above is a conditional bound. Rounding the bar top to the nearest pixel contributes at most one half of the absolute linear slope in data units, if the direction, tick positions and calibration are exact. Disagreement in tick labels can make the scale error much larger than this bound. A reader who applies the half-pixel bound indiscriminately to every part of chart reading may understate uncertainty. The new diagnostic therefore retains the bar pixels and perturbs one label. Expect any resulting difference in the recovered numbers to come from calibration, not from bar detection.
There are charts where several axes or marks encode different units or data series. A multi-axis plot can place separate quantities on the same drawable coordinate system without making their numeric scales equal. Legends, axes and labels are evidence for associations and need to be carried into any parsed representation. Grouped or stacked bars also require a clear rule about whether a top coordinate or the difference between consecutive segment edges encodes a value. A benchmark designed for plain bars only supports plain-bar claims. Verify which kinds of mark and which axis conventions each test actually uses.
From chart pixels to numbers
A chart reader must connect the mark to its label and calibrate the axis. For a linear vertical axis, pixel rows can increase downward while values increase upward, so the fitted slope is negative. If 10 and 20 occur at rows 300 and 200, the row at 250 represents . For a logarithmic axis, the analogous interpolation is in log values and only for valid positive calibration ticks. Labels, scale and mark identification are different error sources.
ChartQA includes questions about visual chart elements as well as arithmetic or logical operations. It is useful to check underlying value extraction before comparing reasoning on retrieved values. The fixture below draws four colored bars and six ticks. It detects dark tick pixels in a known column and identifies bar regions by their exact fill color. Correctly transcribed tick values and the left-to-right label order are supplied as annotations. This is pixel sampling with known color and annotation, rather than a general chart parser.
PythonIn [15]Expand
MARK = (38, 83, 150)
CHART_VALUES = (12, 15, 9, 22)
CHART_LABELS = ("Q1", "Q2", "Q3", "Q4")
TICKS = (0, 5, 10, 15, 20, 25)
CHART_X = (104, 182, 260, 338)
def render_chart():
image = Image.new("RGB", (410, 255), "white")
draw = ImageDraw.Draw(image)
font = ImageFont.truetype(font_manager.findfont("DejaVu Sans"), 13)
draw.text((80, 16), "Quarterly Revenue (Millions)", font=font, fill="black")
for tick in TICKS:
y = round(206 - 6.4 * tick)
draw.line((51, y, 58, y), fill="black")
draw.text((24, y - 8), str(tick), font=font, fill="black")
draw.line((60, 46, 60, 206), fill="black")
draw.line((60, 206, 378, 206), fill="black")
for label, x, value in zip(
CHART_LABELS, CHART_X, CHART_VALUES, strict=True
):
y = round(206 - 6.4 * value)
draw.rectangle((x - 18, y, x + 18, 205), fill=MARK)
draw.text((x - 9, 214), label, font=font, fill="black")
return image
def chart_readout(image):
pixels = np.asarray(image)
ordered_ticks = np.flatnonzero((pixels[:, 54] == 0).all(axis=1))[::-1]
slope, offset = np.polyfit(ordered_ticks, TICKS, deg=1)
bars = (pixels == MARK).all(axis=2)
painted_columns = np.flatnonzero(bars.any(axis=0))
regions = np.split(
painted_columns, np.flatnonzero(np.diff(painted_columns) > 1) + 1
)
tops = [
int(np.flatnonzero(bars[:, cols].any(axis=1))[0]) for cols in regions
]
return ordered_ticks, tops, slope, offset, slope * np.asarray(tops) + offset
chart_image = render_chart()
rows, tops, slope, intercept, values = chart_readout(chart_image)
errors = np.abs(values - np.asarray(CHART_VALUES))VisualizationOut [16]Expand

ConsoleOut [17]Expand
Detected tick rows: [206, 174, 142, 110, 78, 46] Detected bar-top rows: [129, 110, 148, 65] Fit: slope -0.15625 million units per pixel; intercept 32.18750 Q1: recovered 12.03125; actual 12 Q2: recovered 15.00000; actual 15 Q3: recovered 9.06250; actual 9 Q4: recovered 22.03125; actual 22 Maximum absolute error: 0.06250 million units
The largest absolute error is about 0.0625 million units on this fixture. With exact tick rows and a renderer that rounds each bar top to the nearest pixel, the bar rounding error is at most half a pixel times the absolute fitted slope. That gives about 0.0781 million units here. Missing tick marks, antialiasing, overlapping marks or a wrongly selected scale can invalidate this bound. A numeric label or a companion data table can provide an exact value when the bar position is only an estimate.
Calibrating with one inconsistent tick
Use the six actual detected tick rows. Make a copy of their declared values and increase the value 10 to 15 at the third tick. Keep every pixel, bar label and other assigned tick value identical. Fit a second line and measure the observed-versus-fitted discrepancies against the values provided to each fit. Then compare what the two calibrations imply for the original bar tops.
PythonIn [18]Expand
reference_ticks = np.asarray(TICKS, dtype=float)
inconsistent_ticks = reference_ticks.copy()
inconsistent_ticks[2] += 5.0
altered_slope, altered_intercept = np.polyfit(rows, inconsistent_ticks, deg=1)
tick_residuals = reference_ticks - (slope * rows + intercept)
altered_residuals = inconsistent_ticks - (
altered_slope * rows + altered_intercept
)
altered_values = altered_slope * np.asarray(tops) + altered_intercept
largest_residual_index = int(np.argmax(np.abs(altered_residuals)))
assert np.allclose(tick_residuals, 0)
assert largest_residual_index == 2ConsoleOut [19]Expand
Largest absolute reference residual: 0.000 Largest absolute altered residual: 4.095 at pixel row 142 Q1: original 12.031; altered 12.878 Q2: original 15.000; altered 15.762 Q3: original 9.062; altered 9.994 Q4: original 22.031; altered 22.592
VisualizationOut [20]Expand

The largest absolute residual points to the deliberately changed tick row in this setup. That conclusion uses the known fault introduced by the fixture. An unexplained residual on a new chart would require investigating tick association, coordinate detection and the choice of linear scale. The fit with the altered label also changes all four recovered values even though the bar-top rows never moved. A check that only inspects those four pixel rows would miss the calibration error.
Why a graph needs both structure and execution semantics
A diagram can preserve the full inventory of visible node names while communicating a different workflow if one edge was directed incorrectly or got the wrong label. An arrow between two components can represent order, a data dependency or a conditional next action. The task specifies which semantics matter and any instruction on whether connectors with no arrows are undirected. Diagram parsing can therefore produce a typed directed graph for a particular family without asserting that every visual connector should be interpreted that way.
A graph witness can answer a query by naming a source, a normalized relation and a successor. When several edges share the same normalized label from one source, the intended behavior might be branching, ambiguity or invalid input depending on the diagram convention. In the exercise, an absent exact label returns no successor. Preserving this outcome distinguishes missing evidence from a confident answer inferred from nearby words. For a multi-step query, keep the path or subgraph needed to justify the terminal node so that a bad intermediate edge remains visible.
Edge precision and recall are useful when scoring extracted structure. If labels are part of edge identity, changing “no” to “yes” for the same ordered endpoints replaces a correct edge with an incorrect edge. Under a protocol that ignores labels, the structure of that edge can still count as correct. Neither measurement is universally preferable. An accessibility description concerned with connectivity can use an unlabeled graph, while a workflow that follows conditional branches needs accurate labels. A model that succeeds on one local branch should still be tested on reachable endpoints and cases with multiple steps if the deployment needs full path accuracy.
When several different diagrams depict the same process, a parser can be tested separately on invariance to rearranging boxes and on sensitivity to changing edge semantics. The first experiment preserves the graph while changing its appearance. The second preserves much of the appearance while changing one condition. Storing the intended graph directly makes both experiments reproducible. In our synthetic drawing the graph is the starting point for the illustration; the notebook deliberately perturbs that graph to teach scoring. A raster-only reconstruction system would need to detect nodes, connect arrows to endpoints, associate labels and handle occlusion before that score could be reported as extraction from pixels.
Branch labels turn a diagram into a directed graph
A flowchart can use shapes and text to identify nodes, then directed, labeled relations to specify transitions. AI2D describes diagrams with explicit structural annotations. Our small graph is supplied as ground truth. To isolate a parsing error, keep the nodes and endpoint pairs correct but relabel one edge. Measure label-aware edge F1 as when the denominator is positive. A query that requires one unique successor abstains when none or more than one matches.
PythonIn [21]Expand
EDGES = {
("receive", "stock", ""),
("stock", "fulfill", "yes"),
("stock", "backorder", "no"),
("fulfill", "notify", ""),
("backorder", "notify", ""),
}
def successor(edges, source, label):
matches = sorted(
end
for start, end, branch in edges
if start == source and branch == label
)
return matches[0] if len(matches) == 1 else None
missed = (EDGES - {("stock", "backorder", "no")}) | {
("stock", "backorder", "yes")
}
edge_pairs = {"Reference": EDGES, "Relabeled": missed}ConsoleOut [22]Expand
Reference node endpoint count: 5 Labeled edge F1: 1.0 Unique no branch from stock: backorder Relabeled node endpoint count: 5 Labeled edge F1: 0.8 Unique no branch from stock: None
All five endpoint nodes are still present. The relabeling yields four true positive labeled edges out of five on both sides, so F1 is 0.8. The query fails even though the diagram still contains its boxes and arrows. Recovering the graph makes branching or reachability an ordinary symbolic computation. That computation inherits any mistakes in the graph, which is why a separate structure metric matters.
VisualizationOut [23]Expand

Comments
Add to the conversation
A question, a correction, or an example from your own work.
No comments yet. Be the first to share your thoughts!