Creating and Customizing Charts in Word Documents Using Python
Charts are essential tools for data visualization, transforming abstract numbers into intuitive graphical representations. Embedding charts in Word documents makes reports, proposals, and analysis documents more compelling. The traditional approach of manually inserting charts in Word and editing data one by one is inefficient and prone to inconsistency. By creating charts programmatically with Python, you can build an automated pipeline from data to documents, generating standardized reports with charts in batch. This article introduces how to create multiple chart types in Word documents using Python, including setting chart titles, data series, and axis formats. Why Create Charts Programmatically Compared to manual operation, the programmatic approach offers the following advantages: - Batch generation: Automatically generate multiple report documents with charts from data sources - Data synchronization: Chart data comes directly from program variables or database queries, ensuring real-time accuracy - Consistent styling: Uniformly define chart dimensions, title formats, and axis styles through code, eliminating human inconsistency - Pipeline integration: Embed chart creation into document automation workflows, achieving end-to-end automation from data collection to report generation Environment Setup This article uses Spire.Doc for Python, which provides APIs for inserting and customizing charts in Word documents. pip install Spire.Doc After installation, you can import the relevant modules in your Python script and start working. Creating a Column Chart Column charts are one of the most commonly used chart types, suitable for comparing values across categories. The following code demonstrates how to create a column chart with a data series: from spire.doc import * outputFile = "ColumnChart.docx" # Create a document and add a section document = Document() section = document.AddSection() # Add descriptive text section.AddParagraph().AppendText("Column chart.") # Add a paragraph to host the chart newPara = section.AddParagraph() # Append a column chart with specified width and height shape = newPara.AppendChart(ChartType.Column, float(500), float(300)) chart = shape.Chart # Clear default data series chart.Series.Clear() # Add a custom data series chart.Series.Add("Test Series", ["Word", "PDF", "Excel", "GoogleDocs", "Office"], [ float(1900000), float(850000), float(2100000), float(600000), float(1500000) ]) # Set Y-axis number format chart.AxisY.NumberFormat.FormatCode = "#,##0" # Save the document document.SaveToFile(outputFile, FileFormat.Docx) document.Dispose() The generated Word document: Key steps in the code: - Append chart: The AppendChart(ChartType.Column, width, height) method adds a chart shape to the paragraph and returns a chart shape object. - Data series: The Series.Add() method accepts three parameters - series name, category list (X-axis), and value list (Y-axis). - Axis format: AxisY.NumberFormat.FormatCode sets the display format for Y-axis labels."#,##0" applies thousand separators. Creating a Line Chart with Title Line charts are ideal for showing trends over time or categories. The following code creates a line chart with multiple data series and a chart title: from spire.doc import * outputFile = "LineChart.docx" document = Document() section = document.AddSection() section.AddParagraph().AppendText("Line chart.") newPara = section.AddParagraph() # Append a line chart shape = newPara.AppendChart(ChartType.Line, 500.0, 300.0) chart = shape.Chart # Set chart title title = chart.Title title.Text = "My Chart" title.Show = True title.Overlay = True # Add multiple data series seriesColl = chart.Series seriesColl.Clear() categories = ["C1", "C2", "C3", "C4", "C5", "C6"] seriesColl.Add("AW Series 1", categories, [1.0, 2.0, 2.5, 4.0, 5.0, 6.0]) seriesColl.Add("AW Series 2", categories, [2.0, 3.0, 3.5, 6.0, 6.5, 7.0]) document.SaveToFile(outputFile, FileFormat.Docx) document.Dispose() The generated Word document: Title settings explained: - title.Text : Sets the title text content - title.Show : Controls whether the title is displayed - title.Overlay : When set toTrue , the title overlays the chart without taking up additional space Creating a Pie Chart Pie charts display the proportional relationship of parts to a whole. A pie chart requires only one data series: from spire.doc import * outputFile = "PieChart.docx" document = Document() section = document.AddSection() section.AddParagraph().AppendText("Pie chart.") newPara = section.AddParagraph() # Append a pie chart shape = newPara.AppendChart(ChartType.Pie, 500.0, 300.0) chart = shape.Chart # Add a data series chart.Series.Add("Test Series", ["Word", "PDF", "Excel"], [2.7, 3.2, 0.8]) document.SaveToFile(outputFile, FileFormat.Docx) document.Dispose() The data series addition works the same way as with column charts. ChartType.Pie specifies the chart type as a pie chart. Creating Scatter and Bubble Charts Scatter charts show the correlation between two sets of data, while bubble charts add a third dimension to represent data weight. Scatter chart: from spire.doc import * outputFile = "ScatterChart.docx" document = Document() section = document.AddSection() section.AddParagraph().AppendText("Scatter chart.") newPara = section.AddParagraph() # Append a scatter chart shape = newPara.AppendChart(ChartType.Scatter, 450.0, 300.0) chart = shape.Chart chart.Series.Clear() # Add a data series with X and Y value lists chart.Series.Add("Scatter chart", [1.0, 2.0, 3.0, 4.0, 5.0], [1.0, 20.0, 40.0, 80.0, 160.0]) document.SaveToFile(outputFile, FileFormat.Docx) document.Dispose() Bubble chart: from spire.doc import * outputFile = "BubbleChart.docx" document = Document() section = document.AddSection() section.AddParagraph().AppendText("Bubble chart.") newPara = section.AddParagraph() # Append a bubble chart shape = newPara.AppendChart(ChartType.Bubble, float(500), float(300)) chart = shape.Chart chart.Series.Clear() # Add a data series with X, Y, and bubble size lists chart.Series.Add("Test Series", [2.9, 3.5, 1.1, 4.0, 4.0], [1.9, 8.5, 2.1, 6.0, 1.5], [9.0, 4.5, 2.5, 8.0, 5.0]) document.SaveToFile(outputFile, FileFormat.Docx) document.Dispose() The key difference lies in the number of parameters passed to Series.Add() : scatter charts take X and Y lists, while bubble charts take an additional third list for bubble sizes. Creating a 3D Surface Chart 3D surface charts are suitable for displaying the three-dimensional distribution of multivariate data. The following code creates a surface chart with three data series: from spire.doc import * outputFile = "Surface3DChart.docx" document = Document() section = document.AddSection() section.AddParagraph().AppendText("Surface3D chart.") newPara = section.AddParagraph() # Append a 3D surface chart shape = newPara.AppendChart(ChartType.Surface3D, 500.0, 300.0) chart = shape.Chart chart.Series.Clear() # Set title chart.Title.Text = "My chart" # Add multiple data series categories = ["Word", "PDF", "Excel", "GoogleDocs", "Office"] chart.Series.Add("Series 1", categories, [1900000.0, 850000.0, 2100000.0, 600000.0, 1500000.0]) chart.Series.Add("Series 2", categories, [900000.0, 50000.0, 1100000.0, 400000.0, 250000.0]) chart.Series.Add("Series 3", categories, [500000.0, 820000.0, 1500000.0, 400000.0, 100000.0]) document.SaveToFile(outputFile, FileFormat.Docx) document.Dispose() By adding multiple data series, the surface chart can simultaneously display the 3D distribution of multiple data groups, making it suitable for comparative analysis. Practical Tips Auto-Selecting Chart Types Based on Data In practice, you can encapsulate chart creation in a function to quickly add multiple charts to a single document: def create_chart(document, chart_type, title, categories, values): section = document.AddSection() section.AddParagraph().AppendText(title) para = section.AddParagraph() shape = para.AppendChart(chart_type, 500.0, 300.0) chart = shape.Chart chart.Series.Clear() chart.Title.Text = title chart.Title.Show = True chart.Series.Add("Data", categories, values) return chart # Usage example doc = Document() create_chart(doc, ChartType.Column, "Quarterly Sales", ["Q1", "Q2", "Q3", "Q4"], [120.0, 150.0, 180.0, 200.0]) create_chart(doc, ChartType.Line, "Monthly Growth Trend", ["Jan", "Feb", "Mar", "Apr", "May", "Jun"], [10.0, 15.0, 22.0, 28.0, 35.0, 42.0]) doc.SaveToFile("Report.docx", FileFormat.Docx) doc.Dispose() After encapsulating chart creation as a function, you can quickly add various chart types to the same document, which is useful for generating comprehensive reports with multiple data views. Setting Axis Number Formats For large numerical data, setting axis number formats improves readability: # Thousand separator format chart.AxisY.NumberFormat.FormatCode = "#,##0" # Percentage format chart.AxisY.NumberFormat.FormatCode = "0%" # Thousand separator with decimal places chart.AxisY.NumberFormat.FormatCode = "#,##0.00" Conclusion This article covered the complete workflow for creating charts in Word documents using Python, including six chart types: column, line, pie, scatter, bubble, and 3D surface charts. Key takeaways: - Use AppendChart(ChartType, width, height) to append a chart to a paragraph, specifying the chart type via theChartType enum - Add data series with chart.Series.Add() - the number of parameters varies by chart type (scatter charts need X/Y lists, bubble charts need X/Y/size lists) - Set chart title text, visibility, and overlay using chart.Title - Customize axis number display format with chart.AxisY.NumberFormat.FormatCode With these skills, you can integrate chart creation into report generation pipelines, automatically producing Word documents with visualized charts from business data, significantly improving the efficiency and consistency of data report generation. Top comments (0)
Comments
No comments yet. Start the discussion.