Create Stacked Charts in PowerPoint with JavaScript in React

When several series sit side by side under each category, a clustered column chart places them in parallel: readers have to add the column heights themselves to get the total, and it is hard to see how much of the total each part takes up. A stacked chart piles the segments of one category into a single column, where the full height is the category total and each segment is one series' share, so total and composition are read at once. Absolute values versus percentages is the most common way a stacked chart changes, and each reading suits a different situation. This article uses Spire.Presentation for JavaScript to create PowerPoint presentations with stacked charts in a React project. The whole process runs locally on the user's device through WebAssembly, requires no Office installation and no back-end service, and keeps the presentation from leaving the browser.

The article covers two core features:

For installation and project configuration, see Integrating Spire.Presentation for JavaScript in a React Project. The examples below assume that Spire.Presentation for JavaScript is installed and the WebAssembly module has been initialized.


Create a Stacked Column Chart

To put a category's total and the make-up of its series into a single column, start the base chart as a stacked column chart: the series of one category are no longer placed side by side but piled up in turn, where the top of the column corresponds to the sum of all series and each segment to the value of one series. The chart keeps the height comparison between totals while making clear which series add up to each total.

Writing Result
slide.Shapes.AppendChart({ type: ChartType.ColumnStacked, rectangle, init }) Inserts a stacked column chart at the specified position
chart.ChartTitle.TextProperties.Text and chart.HasTitle = true Sets and shows the chart title
chart.ChartData.get_Item({ row, column }).Text / NumberValue Writes the category names, series names and the value of each category
chart.Series.SeriesLabel and chart.Categories.CategoryLabels Binds the series names and the category labels
chart.Series.get_Item(i).Values Binds the value range of the i-th series

The steps are:

  1. Get the Spire.Presentation WASM module, confirm it is ready, load the font file, then create a blank presentation with new Presentation() and get the first slide.
  2. Use RectangleF.FromLTRB() to set the chart rectangle, then call Shapes.AppendChart() with ChartType.ColumnStacked to insert a stacked column chart.
  3. Set ChartTitle.TextProperties.Text and set HasTitle to true so the chart shows its title.
  4. Write the category and series names through Text of ChartData.get_Item(), and write the value of each series in each category through NumberValue.
  5. Bind the series names and category labels with Series.SeriesLabel and Categories.CategoryLabels, then bind each series' value range with Series.get_Item(i).Values; the series stack from bottom to top in the order they are bound.
  6. Call Presentation.SaveToFile() to save the result file, release the presentation with Dispose(), then read the file from VFS and trigger the download.

The code for creating a stacked column chart is as follows:

function App() {
  // create a stacked column chart
  const createStackedColumn = async () => {
    // get the Spire.Presentation WASM module
    const pptModule = window.wasmModule?.spirepresentation;

    // check whether the module is ready
    if (!pptModule) {
      alert('Spire.Presentation is not ready yet');
      return;
    }

    // load the font so that the text in the chart renders correctly
    await window.spire.FetchFileToVFS('ARIAL.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/font/`);

    // create a blank presentation and get the first slide
    const ppt = new pptModule.Presentation();
    const slide = ppt.Slides.get_Item(0);

    // insert a stacked column chart on the slide
    const rect = pptModule.RectangleF.FromLTRB(80, 100, 660, 430);
    const chart = slide.Shapes.AppendChart({ type: pptModule.ChartType.ColumnStacked, rectangle: rect, init: false });

    // set the chart title
    chart.ChartTitle.TextProperties.Text = 'Quarterly Sales by Product';
    chart.ChartTitle.TextProperties.IsCentered = true;
    chart.ChartTitle.Height = 30;
    chart.HasTitle = true;

    // prepare the data of the three series
    const quarters = ['Q1', 'Q2', 'Q3', 'Q4'];
    const laptops = [210, 240, 225, 260];
    const tablets = [140, 150, 170, 160];
    const phones = [180, 200, 190, 230];

    // write the category and series names
    chart.ChartData.get_Item({ row: 0, column: 0 }).Text = 'Quarter';
    chart.ChartData.get_Item({ row: 0, column: 1 }).Text = 'Laptops';
    chart.ChartData.get_Item({ row: 0, column: 2 }).Text = 'Tablets';
    chart.ChartData.get_Item({ row: 0, column: 3 }).Text = 'Smartphones';

    // write the values of each category
    for (let i = 0; i < quarters.length; i++) {
      chart.ChartData.get_Item({ row: i + 1, column: 0 }).Text = quarters[i];
      chart.ChartData.get_Item({ row: i + 1, column: 1 }).NumberValue = laptops[i];
      chart.ChartData.get_Item({ row: i + 1, column: 2 }).NumberValue = tablets[i];
      chart.ChartData.get_Item({ row: i + 1, column: 3 }).NumberValue = phones[i];
    }

    // bind the series names, category labels and value ranges
    chart.Series.SeriesLabel = chart.ChartData.get_Item({ name: 'B1', endCellName: 'D1' });
    chart.Categories.CategoryLabels = chart.ChartData.get_Item({ name: 'A2', endCellName: 'A5' });
    chart.Series.get_Item(0).Values = chart.ChartData.get_Item({ name: 'B2', endCellName: 'B5' });
    chart.Series.get_Item(1).Values = chart.ChartData.get_Item({ name: 'C2', endCellName: 'C5' });
    chart.Series.get_Item(2).Values = chart.ChartData.get_Item({ name: 'D2', endCellName: 'D5' });

    // save the result file
    const outputFileName = 'StackedColumn_result.pptx';
    ppt.SaveToFile({ file: outputFileName, fileFormat: pptModule.FileFormat.Pptx2013 });
    ppt.Dispose();

    // read the generated file from VFS and trigger the download
    downloadFile(outputFileName);
  };

  // read the generated file from VFS and trigger the download
  const downloadFile = (outputFileName) => {
    const fileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);
    const blob = new Blob([fileArray], { type: 'application/vnd.openxmlformats-officedocument.presentationml.presentation' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = outputFileName;
    a.click();
    URL.revokeObjectURL(url);
  };

  return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Create a Stacked Chart in PowerPoint</h1>
      <button onClick={createStackedColumn}>Create Stacked Column Chart</button>
    </div>
  );
}

export default App;

The presentation after creating a stacked column chart:

The presentation after creating a stacked column chart


Create a 100% Stacked Column Chart

When the totals of different categories vary widely, a stacked column chart gives most of the vertical space to the largest category while the smallest category is left with a very short column, making the proportions between segments hard to compare. A 100% stacked column chart normalizes every column to 100%, so each segment keeps only its share of the category total and categories with different totals can be compared by composition side by side. Change the chart type to ChartType.Column100PercentStacked and set the value axis scale to percentages to get such a chart.

Writing Result
slide.Shapes.AppendChart({ type: ChartType.Column100PercentStacked, rectangle, init }) Inserts a 100% stacked column chart that normalizes each category to 100%
chart.PrimaryValueAxis.NumberFormat = '0%' Shows the value axis scale as percentages

The steps are:

  1. Get the Spire.Presentation WASM module, confirm it is ready, load the font file, then create a blank presentation with new Presentation() and get the first slide.
  2. Use RectangleF.FromLTRB() to set the chart rectangle, then call Shapes.AppendChart() with ChartType.Column100PercentStacked to insert a 100% stacked column chart.
  3. Set the chart title, then write the category names, series names and the value of each category through ChartData.get_Item().
  4. Bind the series names, category labels and value ranges with Series.SeriesLabel, Categories.CategoryLabels and Series.get_Item(i).Values.
  5. Set PrimaryValueAxis.NumberFormat to '0%', so the value axis scale shows percentages that match the normalized columns.
  6. Call Presentation.SaveToFile() to save the result file, release the presentation with Dispose(), then read the file from VFS and trigger the download.

The code for creating a 100% stacked column chart is as follows:

function App() {
  // create a 100% stacked column chart
  const createPercentStackedColumn = async () => {
    // get the Spire.Presentation WASM module
    const pptModule = window.wasmModule?.spirepresentation;

    // check whether the module is ready
    if (!pptModule) {
      alert('Spire.Presentation is not ready yet');
      return;
    }

    // load the font so that the text in the chart renders correctly
    await window.spire.FetchFileToVFS('ARIAL.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/font/`);

    // create a blank presentation and get the first slide
    const ppt = new pptModule.Presentation();
    const slide = ppt.Slides.get_Item(0);

    // insert a 100% stacked column chart on the slide
    const rect = pptModule.RectangleF.FromLTRB(80, 100, 660, 430);
    const chart = slide.Shapes.AppendChart({ type: pptModule.ChartType.Column100PercentStacked, rectangle: rect, init: false });

    // set the chart title
    chart.ChartTitle.TextProperties.Text = 'Quarterly Sales by Product';
    chart.ChartTitle.TextProperties.IsCentered = true;
    chart.ChartTitle.Height = 30;
    chart.HasTitle = true;

    // prepare the data of the three series
    const quarters = ['Q1', 'Q2', 'Q3', 'Q4'];
    const laptops = [210, 240, 225, 260];
    const tablets = [140, 150, 170, 160];
    const phones = [180, 200, 190, 230];

    // write the category and series names
    chart.ChartData.get_Item({ row: 0, column: 0 }).Text = 'Quarter';
    chart.ChartData.get_Item({ row: 0, column: 1 }).Text = 'Laptops';
    chart.ChartData.get_Item({ row: 0, column: 2 }).Text = 'Tablets';
    chart.ChartData.get_Item({ row: 0, column: 3 }).Text = 'Smartphones';

    // write the values of each category
    for (let i = 0; i < quarters.length; i++) {
      chart.ChartData.get_Item({ row: i + 1, column: 0 }).Text = quarters[i];
      chart.ChartData.get_Item({ row: i + 1, column: 1 }).NumberValue = laptops[i];
      chart.ChartData.get_Item({ row: i + 1, column: 2 }).NumberValue = tablets[i];
      chart.ChartData.get_Item({ row: i + 1, column: 3 }).NumberValue = phones[i];
    }

    // bind the series names, category labels and value ranges
    chart.Series.SeriesLabel = chart.ChartData.get_Item({ name: 'B1', endCellName: 'D1' });
    chart.Categories.CategoryLabels = chart.ChartData.get_Item({ name: 'A2', endCellName: 'A5' });
    chart.Series.get_Item(0).Values = chart.ChartData.get_Item({ name: 'B2', endCellName: 'B5' });
    chart.Series.get_Item(1).Values = chart.ChartData.get_Item({ name: 'C2', endCellName: 'C5' });
    chart.Series.get_Item(2).Values = chart.ChartData.get_Item({ name: 'D2', endCellName: 'D5' });

    // show the value axis scale as percentages
    chart.PrimaryValueAxis.NumberFormat = '0%';

    // save the result file
    const outputFileName = 'PercentStackedColumn_result.pptx';
    ppt.SaveToFile({ file: outputFileName, fileFormat: pptModule.FileFormat.Pptx2013 });
    ppt.Dispose();

    // read the generated file from VFS and trigger the download
    downloadFile(outputFileName);
  };

  // read the generated file from VFS and trigger the download
  const downloadFile = (outputFileName) => {
    const fileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);
    const blob = new Blob([fileArray], { type: 'application/vnd.openxmlformats-officedocument.presentationml.presentation' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = outputFileName;
    a.click();
    URL.revokeObjectURL(url);
  };

  return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Create a Stacked Chart in PowerPoint</h1>
      <button onClick={createPercentStackedColumn}>Create 100% Stacked Column Chart</button>
    </div>
  );
}

export default App;

The presentation after creating a 100% stacked column chart:

The presentation after creating a 100% stacked column chart


Frequently Asked Questions

Stacked column chart or clustered column chart: which should I choose

Reason: Both chart types draw the series of one category in the same place; the difference is how the series are arranged. A clustered column chart places the series side by side, which suits comparing the height of each series; a stacked column chart piles them up, which suits reading the total and the make-up of that total.

Solution: When you need to compare the values of each series, insert a clustered column chart with ChartType.ColumnClustered; when you need to highlight the total and its composition, insert a stacked column chart with ChartType.ColumnStacked. Both use the same data, so switching the view only takes a change of chart type:

const chart = slide.Shapes.AppendChart({ type: pptModule.ChartType.ColumnStacked, rectangle: rect, init: false });

How do I hide the gridlines of a stacked chart's value axis

Reason: The horizontal gridlines that are on by default cross the stacked columns, and the boundaries between segments overlap the gridlines, which looks cluttered.

Solution: Set the fill type of the value axis major gridlines to FillFormatType.None to hide the gridlines without affecting the columns themselves:

chart.PrimaryValueAxis.MajorGridTextLines.FillType = pptModule.FillFormatType.None;

How do I show the value of each segment on a stacked chart

Reason: A stacked chart only gives the height of each segment; the exact value still has to be estimated against the value axis, which is hard to read when there are many segments.

Solution: Turn on the data labels of the series explicitly, and the value of that series in each category appears next to each segment:

chart.Series.get_Item(0).DataLabels.LabelValueVisible = true;

Get a Free License

If you wish to delete the evaluation message from the resulting documents, or to get rid of function limitations, please contact sales to obtain a valid 30-day temporary license.