DEV Community

jiang jinfeng
jiang jinfeng

Posted on

A Chart Is Four Systems in a Trench Coat

A Chart Is Four Systems in a Trench Coat

go-pptx Tech Blog · Part 5: The Chart Subsystem — From Restricted Types to Combo Charts and Embedded Workbooks

Series: go-pptx Tech Blog (10 parts)
Baseline: v2.4.4
Keywords: ChartML, embedded workbook, combo charts, secondary axis, series labels, canonical validation, client compatibility


1. Why charts are much harder than "drawing a bar"

A PPT chart involves at least four layers:

  1. Chart XML (c:chartSpace): chart type, series, axes, legend, labels, styles;
  2. Embedded workbook (xlsx Part): the chart's "data source", which PowerPoint reads when you open "Edit Data";
  3. Cached data (c:strCache / c:numCache): lets the chart display without opening the workbook;
  4. Relationships and content types: the slide → chart → workbook rels chain and [Content_Types].xml.

These four layers must stay consistent. Change only the chart XML and not the workbook, and "Edit Data" in PowerPoint will show stale values; change only the cache and not the formula references, and clients may display inconsistently; if the workbook's sheet name, column order, or series order don't match, the chart will be misaligned.

So go-pptx's chart implementation is not "stitching together a chunk of XML"; it treats a chart as a restricted subsystem with an explicit contract:

  • Input: ChartSpec (type, categories, series, position, axis options, labels, styles);
  • Output: chart Part + embedded xlsx + slide relationships + content types;
  • Validation: run canonical validation after building; reject non-canonical structures in SetData;
  • Compatibility: tighten the allowlist according to what PowerPoint / WPS / LibreOffice actually accept.

2. Supported chart types

There are currently 9 supported types:

Type ChartType Main elements
Bar chart ChartBar barChart + catAx/valAx
Line chart ChartLine lineChart + catAx/valAx
Pie chart ChartPie pieChart, no axes
Doughnut chart ChartDoughnut doughnutChart, holeSize=50
Area chart ChartArea areaChart + catAx/valAx
Radar chart ChartRadar radarChart (marker)
3D bar chart ChartBar3D bar3DChart + view3D
Scatter chart ChartScatter scatterChart + xVal/yVal + two valAx
Bubble chart ChartBubble bubbleChart + xVal/yVal/bubbleSize

All these types go through the same internal/chart build/parse/validate/workbook-sync path. Adding a type is not "copy-pasting a builder"; it means updating in sync:

  • types.go: the type enum and PlotElement();
  • build.go: chart groups, axes, series references;
  • parse.go: read-back;
  • canonical.go: allowlist validation;
  • workbook.go: column layout (categories/X values, series values, bubble sizes);
  • tests and client re-save verification.

3. Build flow: from ChartSpec to chart Part + xlsx

A typical bar + line combo chart:

spec := pptx.ChartSpec{
    Type:       pptx.ChartBar,
    Title:      "Quarterly Revenue and Growth Rate",
    Categories: []string{"Q1", "Q2", "Q3", "Q4"},
    Series: []pptx.ChartSeries{
        {Name: "Revenue", Values: []float64{120, 135, 150, 168}},
    },
    LineSeries: []pptx.ChartSeries{
        {Name: "Growth Rate", Values: []float64{12, 12.5, 11.1, 12}},
    },
    SecondaryAxis: true, // the line uses the secondary axis
    X: 914400, Y: 914400, Width: 6096000, Height: 3429000,
}

shape, err := slide.AddChart(ctx, spec)
Enter fullscreen mode Exit fullscreen mode

Internally, it roughly does the following:

  1. Allocate chart Part names (e.g. /ppt/charts/chart1.xml) and workbook Part names;
  2. Build the chartSpace XML:
    • c:chart → c:plotArea;
    • primary barChart + overlay lineChart;
    • shared axis or secondary axis (SecondaryAxis);
    • c:ser's c:tx / c:cat / c:val references;
    • title, legend, labels, styles, axis options;
  3. Build the embedded xlsx:
    • [Content_Types].xml, _rels/.rels, xl/workbook.xml, xl/worksheets/sheet1.xml;
    • row 1 for series names, rows 2..n+1 for categories + values;
    • for scatter/bubble charts, column A holds X values; bubble charts additionally write a size column;
  4. Establish relationships: slide → chart, chart → workbook, chart → embedded object;
  5. Commit as a single multi-Part transaction.

The workbook's column layout must strictly match the formula references in the chart XML. For example, the primary series starts at column B, and overlay series follow right after; if the series order changes, the column references must change too. BuildChartSpaceXML writes column references using a series offset to avoid misalignment.


4. Combo charts and secondary axes

4.1 Bar + line

ChartSpec{
    Type:       ChartBar,
    Series:     []ChartSeries{{Name: "Revenue", Values: ...}},
    LineSeries: []ChartSeries{{Name: "Growth Rate", Values: ...}},
}
Enter fullscreen mode Exit fullscreen mode
  • plotArea writes barChart + lineChart;
  • shares two axIds;
  • axes are written only once;
  • workbook columns: categories in A, primary series in B.., overlay series right after.

4.2 Bar + line + secondary axis

SecondaryAxis: true
Enter fullscreen mode Exit fullscreen mode
  • the secondary axis IDs are fixed to catAxID+2 / valAxID+2;
  • lineChart uses the secondary axId;
  • plotArea adds a hidden secondary category axis (delete=1) and a right-side secondary value axis (axPos="r");
  • on read-back, SecondaryAxis is inferred from the number of valAx elements.

4.3 Bar + area, area + line

  • ChartSpec/ChartData.AreaSeries: bar primary + area overlay (can coexist with line);
  • ChartArea supports a LineSeries overlay;
  • canonical allows up to 3 plots (bar + line/area);
  • the secondary axis flag also applies to area overlays.

4.4 Secondary-axis series

  • SecondaryLineSeries: a secondary-axis line layer on a line chart;
  • SecondaryBarSeries: a secondary-axis bar layer on a bar chart.

These capabilities were added batch by batch, and each batch updated build / parse / canonical / workbook in sync and performed client re-save verification.


5. Expressiveness of series and axes

5.1 Series-level data labels

ChartSeries{
    Name:   "Revenue",
    Values: []float64{120, 135, 150, 168},
    DataLabel: &pptx.ChartDataLabel{
        Show:     true,
        Position: "ctr", // tightened per chart type
    },
}
Enter fullscreen mode Exit fullscreen mode

The position allowlist is not "write whatever you like":

  • bar / line / line overlay / secondary bar overlay: empty or ctr;
  • area / pie / doughnut / radar / bar3D / area overlay: empty only.

The reason is that PowerPoint will reject the entire package for inapplicable positions. For example, using outB for bar, ctr for area, or ctr for pie/radar/bar3D can all make the file fail to open. go-pptx chooses to "tighten according to client acceptance" rather than "accept every parameter and leave it to luck whether it breaks".

5.2 Series styles

ChartSeries{
    Name: "Revenue",
    Style: &pptx.ChartSeriesStyle{
        Fill:      pptx.ChartColor{RGB: "2E75B6"},
        Line:      pptx.ChartColor{RGB: "1F4E79"},
        LineWidth: 12700,
    },
}
Enter fullscreen mode Exit fullscreen mode

Writes c:ser/c:spPr, supporting solid fills and lines; colors can be sRGB or theme colors.

5.3 Series markers

ChartSeries{
    Name: "Growth Rate",
    Marker: &pptx.ChartMarker{
        Symbol: "circle",
        Size:   6,
        Fill:   pptx.ChartColor{RGB: "2E75B6"},
    },
}
Enter fullscreen mode Exit fullscreen mode

Only effective for line / scatter / bubble series; symbol supports circle/square/diamond/triangle/x/star/dot/plus/dash/none/auto.

5.4 Axis gridlines and number formats

Axes: &pptx.ChartAxisOptions{
    ValueNumberFormat:    "0.0%",
    CategoryNumberFormat: "General",
    ValueMajorGridlines: &pptx.ChartGridlines{
        Line:  pptx.ChartColor{RGB: "D9D9D9"},
        Width: 6350,
    },
}
Enter fullscreen mode Exit fullscreen mode

Writes c:valAx/c:majorGridlines, the numFmt of c:categoryAx, and so on. Number formats matter especially for financial reports: formats like 0.0%, #,##0, ¥#,##0 directly determine the reading experience.


6. Canonical validation: why only "canonical layouts" are accepted

internal/chart/canonical.go defines a strict allowlist. SetData rejects non-canonical chart Parts because:

  • charts rewritten by external tools/clients may contain many extensions this library doesn't understand (spPr, dLbls, trendline, complex layouts);
  • "partial merging" easily produces semantic inconsistency (data changed, styles not changed, cache not changed);
  • rather than guess, it rejects, and lets the caller take the "rebuild the chart" or "keep it as-is" path.

The canonical check covers:

  • c:chartSpace may only contain c:chart;
  • the allowlist and counts of c:chart's child elements;
  • the chart groups, axis counts, and combination legality of plotArea;
  • the child element order and allowed items of c:ser;
  • the subtrees of legend, title, and view3D;
  • the allowlists for extensions such as axes, labels, and styles.

The cost is: non-canonical charts can only be read, not incrementally updated. This is an intentional boundary — the precondition for faithful editing is "I know what I'm changing".


7. Read-back and two-model conversion

v2.4.4 adds:

func ChartDataFromSpec(spec ChartSpec) ChartData
func ChartSpecFromData(data ChartData, x, y, width, height int64) ChartSpec
Enter fullscreen mode Exit fullscreen mode

Uses:

  • read ChartData back from an existing chart, then convert it to ChartSpec for "copy/reconfigure";
  • slices are copied, nested pointers are shared (avoiding deep-copy cost).

The read-back path handles:

  • primary chart type and overlays;
  • categories, series values, X values, bubble sizes;
  • title/rich-text Runs;
  • legend, labels, styles, markers, gridlines, number formats;
  • the secondary axis flag;
  • the embedded workbook's sheet name and column references.

8. Performance: single traversal and combo paths

Chart parsing once had an obvious performance problem: multiple repeated scans of plotArea. v2.4.4 changes it to:

  1. first collect the chart groups of plotArea;
  2. then dispatch overlays by primary chart type;
  3. complete in a single traversal.

Combo-shape path generation also changed from "repeated concatenation at each layer" to a []string segment stack that concatenates only once when generating the NodePath, eliminating the O(depth²) allocations of deep combinations.

These optimizations don't change semantics, but make large-document / deep-combination / many-chart scenarios more stable.


9. Compatibility and verification

Chart client compatibility is more sensitive than ordinary text because:

  • PowerPoint is very strict about element order, required child elements, and enum values;
  • WPS has its own tolerance;
  • LibreOffice's rendering/re-save behavior is different again.

The project's verification approach is:

  • unit tests: build → parse → rebuild round-trips;
  • canonical tests: illegal combinations must be rejected;
  • workbook tests: column layout and references stay consistent;
  • client re-save: open in PowerPoint 16 / WPS 12 / LibreOffice 24.2, re-save, then re-verify;
  • a 13-page comprehensive sample covering combo charts, labels, styles, markers, gridlines, and number formats.

Known limitations are written into the docs rather than hidden. For example:

  • series label positions are more fully verified only for bar/line; other types support only the default position;
  • the secondary axis is fixed on the right and the category axis is hidden; clients may rearrange axes;
  • legend order may be adjusted by the client;
  • non-canonical charts don't support incremental SetData.

10. Summary

The core of the chart subsystem is not "how many chart types it supports", but four-layer consistency:

  1. the chart XML structure is correct;
  2. the embedded workbook's column layout matches the formula references;
  3. the cached data matches the workbook;
  4. relationships/content types are complete, and clients can open and re-save.

go-pptx uses "restricted types + canonical allowlist + client re-save verification" to guarantee these four layers. It doesn't aim for "any chart can be edited", but for "charts we support, clients accept them after editing".

The next part moves on to media and auto-narration: without installing FFmpeg, how to probe audio/video in pure Go and wire them into playback timing.


Series navigation: ← Part 4: Object Model and Handles · Part 6: Media and Auto-Narration →

Top comments (0)