# Charts

`slide.charts` creates chart elements with slide placement and chart configuration.

## Resolved From Inspect

```ts
const chart = presentation.resolve("ch/b2c3d4e5");
chart.title = "Updated chart title";
chart.yAxis = { numberFormatCode: "$#,##0M" };
chart.series.getItemAt(0).values = [3.1, 3.7, 4.2, 4.8];
```

Use `presentation.inspect({ select, include })` with
`select: "$.slides[*].elements[?(@.kind == 'chart')]"` and
`include: ["id", "title"]` to find the `ch/...`
anchor id. If an imported chart resolves as an image, preserve it as an image or
rebuild it as a native chart intentionally.

## Add Chart

```ts
const chart = slide.charts.add(chartType, {
  position,
  title,
  titleTextStyle,
  categories,
  series,
  groups,
  hasLegend,
  legend,
  barOptions,
  lineOptions,
  areaOptions,
  pieOptions,
  doughnutOptions,
  treemapOptions,
  mapOptions,
  funnelOptions,
  boxWhiskerOptions,
  histogramOptions,
  view3d,
  scatterOptions,
  radarOptions,
  surface,
  bubbleOptions,
  xAxis,
  yAxis,
  secondaryXAxis,
  secondaryYAxis,
  dataLabels,
  dataTable,
  chartFill,
  chartLine,
  plotAreaFill,
  plotAreaLine,
});
```

Small chart option enums are listed below.

Chart `chartLine`, `plotAreaLine`, series `line`, axis `line`, and gridlines
use [LineConfig](./fill.spec.md#line-inline-type). Include `style` even when
hiding a border:

```ts
chart.chartLine = { style: "solid", fill: "none", width: 0 };
chart.yAxis = {
  textStyle: { typeface: "Arial", fontSize: 14, fill: "#475569" },
  majorGridlines: { style: "solid", fill: "#e2e8f0", width: 1 },
};
```

## Chart Inline Types

```ts
type ChartTypeName =
  | "line" | "pie" | "bar" | "doughnut" | "scatter" | "bubble" | "radar"
  | "treemap" | "sunburst" | "map" | "waterfall" | "line3D" | "pie3D"
  | "area3D" | "bar3D" | "funnel" | "histogram" | "boxWhisker" | "stock"
  | "surface3D" | "ofPie" | "surface" | "pareto" | "combo" | "area";

type ChartConfig = {
  position?: { left?: number; top?: number; width?: number; height?: number };
  title?: string;
  roundedCorners?: boolean | null;
  titlePlacement?: "none" | "aboveChart" | "centeredOverlay";
  titleTextStyle?: ChartTextStyleConfig;
  categories?: string[];
  series?: ChartSeriesConfig[];
  groups?: ChartGroupConfig[];
  hasLegend?: boolean;
  legend?: ChartLegendConfig;
  barOptions?: { direction?: "bar" | "column"; grouping?: "clustered" | "stacked" | "percentStacked"; varyColors?: boolean; gapWidth?: number; gapDepth?: number; overlap?: number; bar3dShape?: number };
  lineOptions?: ChartLineOptionsConfig;
  areaOptions?: { grouping?: "standard" | "stacked" | "percentStacked"; varyColors?: boolean; gapDepth?: number };
  pieOptions?: { firstSliceAngle?: number };
  doughnutOptions?: { holeSize?: number; firstSliceAngle?: number };
  treemapOptions?: { parentLabelLayout?: "none" | "overlapping" | "banner" };
  mapOptions?: { mapArea?: "world" | "auto" | "dataOnly" | "region"; projection?: "mercator" | "auto" | "miller" | "albers"; labelLayout?: "none" | "bestFit" | "showAll"; dataLevel?: "auto" | "county" | "postalCode" | "countryOrRegion" | "stateOrProvince" | "stateCode" | "countyCode" | "countryOrRegionCode"; showUnknown?: boolean; onlyRegionsWithData?: boolean };
  funnelOptions?: { gapWidth?: number };
  boxWhiskerOptions?: { showMeanLine?: boolean; showMeanMarker?: boolean; showNonOutliers?: boolean; showOutliers?: boolean; quartileMethod?: "inclusive" | "exclusive" };
  histogramOptions?: { binWidth?: number | null; binCount?: number | null; underflow?: number | null; overflow?: number | null; intervalClosed?: number; aggregated?: boolean };
  view3d?: { rotX?: number; rotY?: number; perspective?: number; rightAngleAxes?: boolean; heightPercent?: number; depthPercent?: number };
  scatterOptions?: { style?: "line" | "lineWithMarkers" | "marker" | "smooth" | "smoothWithMarkers"; varyColors?: boolean };
  radarOptions?: { style?: "standard" | "marker" | "filled"; varyColors?: boolean };
  surface?: { // surface and surface3D charts
    wireframe?: boolean;
    bandFormats?: { index: number; fill?: FillConfig; stroke?: LineConfig }[];
    hasBandFormats?: boolean;
    floor?: { fill?: FillConfig; stroke?: LineConfig };
    sideWall?: { fill?: FillConfig; stroke?: LineConfig };
    backWall?: { fill?: FillConfig; stroke?: LineConfig };
  };
  bubbleOptions?: { scale?: number | null; sizeRepresents?: "area" | "width" | null; showNegative?: boolean | null };
  xAxis?: ChartAxisConfig;
  yAxis?: ChartAxisConfig;
  secondaryXAxis?: ChartAxisConfig;
  secondaryYAxis?: ChartAxisConfig;
  dataLabels?: ChartDataLabelsConfig;
  dataTable?: ChartDataTableConfig;
  chartFill?: FillConfig;
  chartLine?: LineConfig;
  plotAreaFill?: FillConfig;
  plotAreaLine?: LineConfig;
  displayBlanksAs?: "zero" | "gap" | "span" | null;
  styleIndex?: number;
};

type ChartLineOptionsConfig = {
  gapDepth?: number; // integer from 0 to 500 for 3D lines
  grouping?: "standard" | "stacked" | "percentStacked";
  smooth?: boolean;
  varyColors?: boolean;
  highLowLine?: LineConfig | null;
  upDownBars?: {
    gapWidth?: number | null;
    upBars?: { fill?: FillConfig | null; stroke?: LineConfig | null } | null;
    downBars?: { fill?: FillConfig | null; stroke?: LineConfig | null } | null;
  } | null;
};
```

## Chart Family Options

`funnelOptions.gapWidth` ranges from 0 to 0.8. `barOptions.gapWidth` is an
integer from 0 to 500.

### 3D Bar Charts

```ts
const bars = slide.charts.add("bar3D", {
  categories: ["Category 1", "Category 2", "Category 3"],
  series: [
    { name: "Series 1", values: [12, 18, 15] },
    { name: "Series 2", values: [8, 14, 10] },
  ],
  barOptions: { direction: "bar", grouping: "clustered" },
  view3d: { rotX: 15, rotY: 20 },
});
bars.barOptions.grouping = "stacked";
```

### 3D Area Charts

`area3D` renders standard, stacked and 100% stacked filled volumes. Standard
series occupy separate depth lanes; stacked series share one lane. Depth spacing
is controlled through `chart.areaOptions.gapDepth`, an integer from 0 to 500
(default 150). Missing samples are plotted at zero, matching PowerPoint.

```ts
const area = slide.charts.add("area3D", {
  categories: ["Q1", "Q2", "Q3"],
  series: [{ name: "Revenue", values: [12, 18, 15], fill: "#156082" }],
  areaOptions: { grouping: "standard", gapDepth: 150 },
  view3d: { rotX: 15, rotY: 20 },
});
area.areaOptions.gapDepth = 50;
```

### Stock Charts

Supply series in High, Low, Close order for HLC, or Open, High, Low, Close
order for OHLC. New stock charts include high-low lines; HLC charts also show
Close markers, and OHLC charts include up/down bars. Set `highLowLine` or
`upDownBars` to `null` to hide it. Set the Close marker's `symbol` to `"none"`
to hide that marker.

```ts
const stock = slide.charts.add("stock", {
  categories,
  series: [
    { name: "Open", values: openValues },
    { name: "High", values: highValues },
    { name: "Low", values: lowValues },
    { name: "Close", values: closeValues },
  ],
  lineOptions: {
    highLowLine: { style: "solid", fill: "#475569", width: 1 },
    upDownBars: {
      gapWidth: 150,
      upBars: { fill: "#16a34a", stroke: { style: "solid", fill: "#166534" } },
      downBars: { fill: "#dc2626", stroke: { style: "solid", fill: "#991b1b" } },
    },
  },
});

stock.lineOptions.highLowLine = { style: "solid", fill: "#334155", width: 2 };
```

`upDownBars.gapWidth` is an integer from 0 to 500. To include volume, create
a combo chart with a primary-axis `bar` group for volume and a secondary-axis
`stock` group for the HLC or OHLC series.

### Combo Charts

```ts
const chart = slide.charts.add("combo", {
  categories,
  groups: [
    {
      type: "bar",
      barOptions: { grouping: "clustered", gapWidth: 150 },
      series: [{ name: firstSeriesName, values: firstValues, fill: firstColor }],
    },
    {
      type: "line",
      axis: "secondary",
      lineOptions: { smooth: false },
      series: [{ name: secondSeriesName, values: secondValues, line: { style: "solid", fill: secondColor, width: 2 } }],
    },
  ],
  yAxis: { min: 0, max: primaryMaximum },
  secondaryYAxis: { min: 0, max: secondaryMaximum, numberFormatCode: "0%" },
});

chart.secondaryYAxis = { max: updatedMaximum };
const group = chart.groups.getItemAt(1);
group.series.getItemAt(0).values = updatedValues;
group.lineOptions.smooth = false;
group.dataLabels.showValue = true;
group.axis = "primary";
group.type = "area";
group.areaOptions.grouping = "stacked";

const series = group.series.add(addedSeriesName);
series.values = addedValues;
group.series.deleteAt(seriesIndex);
chart.groups.add({ type: "line", series: [{ name: addedSeriesName, values: addedValues }] });
chart.groups.deleteAt(groupIndex);
const groupConfigs = chart.groups.toConfig();
chart.groups = replacementGroups;

type ChartGroupConfig = {
  id?: string;
  axis?: "primary" | "secondary";
  series: ChartSeriesConfig[];
  dataLabels?: ChartDataLabelsConfig;
} & (
  | { type: "bar"; barOptions?: { direction?: "column"; grouping?: "clustered" | "stacked" | "percentStacked"; gapWidth?: number; overlap?: number; varyColors?: boolean } }
  | { type: "line"; lineOptions?: ChartLineOptionsConfig }
  | { type: "stock"; lineOptions?: ChartLineOptionsConfig }
  | { type: "area"; areaOptions?: { grouping?: "standard" | "stacked" | "percentStacked"; varyColors?: boolean; gapDepth?: number } }
);
```

`toConfig()` includes group and series IDs. Keep these IDs when editing or
reordering configurations; omit them when adding new groups or series. Group IDs
and series IDs must each be unique within a chart.

Combo charts use `groups` to supply series. Include at least one primary-axis
group. Each group has its own chart family and stacking options; groups sharing
an axis share its scale. `chart.groups.items` contains the editable groups;
`chart.groups.length` gives their count. `chart.series` exposes the same series
in group order. Secondary groups create a right value axis and a hidden category
axis, styled with `secondaryYAxis` and `secondaryXAxis`.

```ts
histogram.histogramOptions = { binWidth: 5 };
histogram.histogramOptions = { binCount: 8, underflow: 0, overflow: 30 };
histogram.histogramOptions = { binWidth: null, binCount: null };
histogram.histogramOptions = { underflow: null, overflow: null };
bubble.bubbleOptions = { scale: 150, sizeRepresents: "area" };
bubble.bubbleOptions = { scale: null, sizeRepresents: null };
bubble.bubbleOptions = { showNegative: true };
```

## Grouped Edits

```ts
chart.xAxis = axisConfig;
chart.yAxis = axisConfig;
chart.legend = legendConfig;
chart.dataLabels = dataLabelsConfig;
chart.dataTable = dataTableConfig;
```

### Data Labels

```ts
chart.dataLabels = { showValue: true, position: "outEnd" };
chart.dataLabels = { textStyle: { fontSize: 14 } };
chart.dataLabels.textStyle = { fontSize: "12pt", bold: true };
chart.dataLabels.showCategoryName = true;

const series = chart.series.getItemAt(seriesIndex);
series.dataLabels = { showValue: false, showSeriesName: true };
series.dataLabels.textStyle = { italic: true };
series.dataLabels.showSeriesName = false;
```

Config assignments update supplied fields and preserve omitted values. New label
collections initialize all seven `show*` flags to `false`. A series without its
own label collection inherits chart labels; omitted point flags inherit series
or chart labels.

### Text Style Edits

```ts
chart.xAxis.textStyle.italic = true;
chart.xAxis.textStyle = { fontSize: 12, bold: true };
chart.yAxis.textStyle = { fontSize: "12pt", color: "#475569" };
```

Style configs update supplied fields and preserve omitted fields.

### Axis Placement

```ts
chart.xAxis = { crossesAt: 2 }; // The value axis crosses at category 2.
chart.yAxis = { crossesAt: 25 }; // The category axis crosses at value 25.
chart.yAxis = { tickLabelPosition: "high" };
```

## Series

```ts
const chart = slide.charts.add(chartType, {
  categories,
  series: [
    {
      name: seriesName,
      categories,
      values,
      xValues,
      categoryPaths,
      fill: fillConfig,
      line: lineConfig,
      marker: markerConfig,
      points,
      dataLabels: dataLabelsConfig,
      dataLabelOverrides,
      trendlines,
      errorBars,
    },
  ],
});
```

## Series Inline Type

Use `chart.series.getItemAt(index)` for a series and
`presentation.slides.getItem(index)` for a slide.

`marker.size` is a diameter in points. If supplied, it must be an integer from
2 through 72, even when `symbol` is `"none"`. To hide a marker, use
`marker: { symbol: "none" }` and omit `size`. `size: 0` is rejected.

Edit an existing series through its marker and collection facades:

```ts
const series = chart.series.getItemAt(seriesIndex);
series.marker = { symbol: "circle", size: 8 };
series.marker.fill = "#2563EB";
series.apply({ name: series.name, points: [{ idx: dataPointIdx, fill: fillConfig }] });
series.dataLabelOverrides.add(dataPointIdx).text = labelText;
```

```ts
type ChartSeriesConfig = {
  id?: string;
  name: string;
  categories?: string[];
  values?: Array<number | null>;
  xValues?: Array<number | null>;
  categoryPaths?: string[][];
  bubbleSizes?: Array<number | null>;
  bubbleSizeFormula?: string;
  bubbleSizesFormatCode?: string;
  explosion?: number;
  smooth?: boolean;
  fill?: FillConfig;
  line?: LineConfig;
  stroke?: LineConfig;
  // Scatter outline color defaults to the marker's solid fill; explicit stroke fills take precedence.
  marker?: { symbol?: "circle" | "diamond" | "dot" | "none" | "plus" | "square" | "star" | "triangle" | "x"; size?: number; fill?: FillConfig; line?: LineConfig };
  points?: Array<{ idx: number; fill?: FillConfig; line?: LineConfig; stroke?: LineConfig }>;
  dataLabels?: ChartDataLabelsConfig;
  dataLabelOverrides?: Array<{ idx: number; text?: string; separator?: string; position?: string; fill?: FillConfig; line?: LineConfig; stroke?: LineConfig; showValue?: boolean; showSeriesName?: boolean; showCategoryName?: boolean; showPercent?: boolean; textStyle?: ChartTextStyleConfig }>;
  trendlines?: Array<{
    type?: "linear" | "exponential" | "logarithmic" | "polynomial" | "power" | "movingAverage";
    name?: string;
    polynomialOrder?: number;
    movingAveragePeriod?: number;
    forecastForward?: number;
    forecastBackward?: number;
    intercept?: number;
    displayEquation?: boolean;
    displayRSquared?: boolean;
    line?: LineConfig;
    label?: { text?: string; textStyle?: ChartTextStyleConfig; fill?: FillConfig; line?: LineConfig };
  }>;
  errorBars?: { type?: "standardError" | "percentage" | "standardDeviation" | "none"; value?: number; endStyle?: "cap" | "noCap"; line?: LineConfig };
  valuesFormatCode?: string;
  xValuesFormatCode?: string;
};
```

## Edit series

Creation configs accept plain objects and arrays. Live `points`,
`dataLabelOverrides`, and `trendlines` are collections. Edit `marker` and
`textStyle` through their properties. These objects already exist, so no
initial assignment is needed. Use `.items` for array methods.

```ts
const seriesNames = chart.series.items.map((series) => series.name);
const series = chart.series.getItemAt(seriesIndex);
series.apply({ name: series.name, points: [{ idx: dataPointIdx, fill: pointFill }] });
series.marker.symbol = "circle";
series.marker.size = 8;
series.dataLabelOverrides.add(dataPointIdx).showValue = true;
chart.xAxis.textStyle.fontSize = 14;
```

To add a linear trendline, call `series.trendlines.add("linear", {})` once.

## Data Label Overrides

```ts
const override = chart.series
  .getItemAt(seriesIndex)
  .dataLabelOverrides.add(dataPointIdx);
override.text = labelText;
override.position = labelPosition;
override.textStyle = { fontSize: 12, bold: true };
override.textStyle.fontSize = fontSizePx;
override.textStyle.fill = textFill;
override.fill = fillConfig;
override.stroke = lineConfig;
```

## Chart Areas

```ts
const chart = slide.charts.add(chartType, {
  chartFill,
  plotAreaFill,
});
```

## Axis, Legend, Label Inline Types

```ts
type ChartTextStyleConfig = {
  typeface?: string;
  fontSize?: number | string; // Numeric pixels or a unit string such as "14pt".
  fontSizePt?: number;
  rotation?: number;
  name?: string;
  family?: number;
  fill?: FillConfig;
  color?: ColorConfig;
  bold?: boolean;
  italic?: boolean;
  underline?: string;
  alignment?: "left" | "center" | "right" | "justify";
};

type ChartLegendConfig = {
  position?: "left" | "top" | "topRight" | "right" | "bottom";
  overlay?: boolean;
  fill?: FillConfig;
  line?: LineConfig;
  textStyle?: ChartTextStyleConfig;
};

type ChartDataLabelsConfig = {
  visible?: boolean;
  deleted?: boolean;
  position?: "center" | "inEnd" | "outEnd" | "left" | "right" | "top" | "bottom" | "insideBase" | "bestFit" | "dataCallout";
  showValue?: boolean;
  showSeriesName?: boolean;
  showCategoryName?: boolean;
  showLegendKey?: boolean;
  showPercent?: boolean;
  showBubbleSize?: boolean;
  showLeaderLines?: boolean;
  numberFormatCode?: string;
  numberFormatSourceLinked?: boolean;
  separator?: string;
  textStyle?: ChartTextStyleConfig;
  fill?: FillConfig;
  line?: LineConfig;
};

type ChartAxisConfig = {
  visible?: boolean;
  title?: string | { text?: string; textStyle?: ChartTextStyleConfig };
  numberFormatCode?: string;
  min?: number;
  max?: number;
  majorUnit?: number;
  minorUnit?: number;
  position?: "bottom" | "left" | "right" | "top";
  tickLabelPosition?: "nextTo" | "high" | "low" | "none" | string;
  labelOffsetPercent?: number; // Category-axis font-size percentage; 0–1000, default 100.
  textStyle?: ChartTextStyleConfig;
  line?: LineConfig;
  majorGridlines?: LineConfig | null;
  minorGridlines?: LineConfig | null;
};
```

Set chart fonts with `textStyle.typeface`, as in
`{ typeface: "Arial", fontSize: 14 }`. Data-label styles also accept the string
alias `fontFamily`; an explicit `typeface` takes precedence. Use booleans for
`bold` and `italic`.

## Cookbook

```ts
// Executive horizontal bar chart.
slide.charts.add("bar", {
  position: { left: 96, top: 160, width: 720, height: 360 },
  categories: ["Enterprise", "Mid-market", "SMB"],
  series: [{ name: "ARR", values: [42, 28, 17], fill: "#2563eb" }],
  barOptions: { direction: "bar", grouping: "clustered", gapWidth: 44 },
  hasLegend: false,
  xAxis: { visible: false, majorGridlines: null },
  yAxis: { textStyle: { fill: "#475569", fontSize: 13 }, line: { style: "solid", fill: "#e2e8f0", width: 1 } },
  dataLabels: { showValue: true, position: "outEnd", textStyle: { fill: "#0f172a", fontSize: 13, bold: true } },
});
```

```ts
// Compact trend line with muted grid.
slide.charts.add("line", {
  position: { left: 96, top: 150, width: 880, height: 280 },
  categories: ["Jan", "Feb", "Mar", "Apr"],
  series: [{ name: "Conversion", values: [31, 34, 37, 43], line: { style: "solid", fill: "#0f766e", width: 3 } }],
  legend: { position: "bottom", overlay: false },
  yAxis: { numberFormatCode: "0%", majorGridlines: { style: "solid", fill: "#e2e8f0", width: 1 } },
});
```

```ts
// Doughnut chart with labels outside.
slide.charts.add("doughnut", {
  categories: ["Product", "Sales", "Support"],
  series: [{ name: "Share", values: [52, 31, 17] }],
  dataLabels: { showPercent: true, showCategoryName: true, position: "outEnd" },
  legend: { position: "right" },
});
```

```ts
// Each doughnut series becomes a ring, from innermost to outermost.
slide.charts.add("doughnut", {
  categories: ["1st Qtr", "2nd Qtr", "3rd Qtr", "4th Qtr"],
  series: [
    { name: "Previous year", values: [8.2, 3.2, 1.4, 1.2] },
    { name: "Current year", values: [5, 6, 7, 8] },
  ],
  doughnutOptions: { holeSize: 75, firstSliceAngle: 50 },
  legend: { position: "bottom" },
});
```

### Surface and contour formatting

```ts
const chart = slide.charts.add("surface3D", {
  categories,
  series,
  surface: {
    wireframe: false,
    floor: { fill: "#eeeeee" },
    sideWall: { fill: "#ddeeff" },
    backWall: { fill: "#ddeeff" },
    bandFormats: [{ index: 0, fill: "#4488cc" }],
  },
});
const surface = chart.surface;
if (!surface) throw new Error("Expected a surface chart");
surface.wireframe = true;
surface.floor.fill = "#ffffff";
surface.backWall.stroke = { fill: "#444444", width: 1 };
```

Use `"surface"` for the contour view. The `surface` facade is available for
`surface` and `surface3D` charts. After changing to another chart family, obtain a
new facade when returning to a surface chart.
