In data visualization scenarios, pie charts and donut charts are ideal choices for displaying proportional relationships and market share. By automating chart generation with Python, data can be efficiently transformed into intuitive visual presentations, suitable for sales reports, market analysis, and management presentations.
This article demonstrates how to create and customize pie charts and donut charts in PowerPoint presentations using Spire.Presentation for Python, covering core functionalities such as data binding, color customization, and label configuration.
Environment Setup
First, install the Spire.Presentation library:
pip install Spire.Presentation
This library provides a comprehensive PowerPoint manipulation API that supports creating various chart types with fine-grained customization options.
Creating Pie Charts
Pie charts are suitable for displaying the proportion of each part relative to the whole. The following example demonstrates how to create a pie chart showing quarterly sales figures.
Basic Implementation Steps
The core process for creating a pie chart includes: initializing the presentation document, adding a chart object, binding data sources, configuring chart properties, and finally saving the file.
from spire.presentation.common import *
from spire.presentation import *
# Create presentation document
presentation = Presentation()
# Add a pie chart to the first slide, setting position and size
rect = RectangleF.FromLTRB(40, 100, 590, 420)
chart = presentation.Slides[0].Shapes.AppendChartInit(ChartType.Pie, rect, False)
# Set chart title
chart.ChartTitle.TextProperties.Text = "Quarterly Sales"
chart.ChartTitle.TextProperties.IsCentered = True
chart.ChartTitle.Height = 30
chart.HasTitle = True
# Define data
quarters = ["Q1", "Q2", "Q3", "Q4"]
sales = [210, 320, 180, 500]
# Write data to chart data table
chart.ChartData[0, 0].Text = "Quarter"
chart.ChartData[0, 1].Text = "Sales"
for i in range(len(quarters)):
chart.ChartData[i + 1, 0].Text = quarters[i]
chart.ChartData[i + 1, 1].NumberValue = sales[i]
# Bind data series
chart.Series.SeriesLabel = chart.ChartData["B1", "B1"]
chart.Categories.CategoryLabels = chart.ChartData["A2", "A5"]
chart.Series[0].Values = chart.ChartData["B2", "B5"]
# Set different colors for each data point
for i in range(len(chart.Series[0].Values)):
cdp = ChartDataPoint(chart.Series[0])
cdp.Index = i
chart.Series[0].DataPoints.Add(cdp)
chart.Series[0].DataPoints[0].Fill.FillType = FillFormatType.Solid
chart.Series[0].DataPoints[0].Fill.SolidColor.Color = Color.get_RosyBrown()
chart.Series[0].DataPoints[1].Fill.FillType = FillFormatType.Solid
chart.Series[0].DataPoints[1].Fill.SolidColor.Color = Color.get_LightBlue()
chart.Series[0].DataPoints[2].Fill.FillType = FillFormatType.Solid
chart.Series[0].DataPoints[2].Fill.SolidColor.Color = Color.get_LightPink()
chart.Series[0].DataPoints[3].Fill.FillType = FillFormatType.Solid
chart.Series[0].DataPoints[3].Fill.SolidColor.Color = Color.get_MediumPurple()
# Display value and percentage labels
chart.Series[0].DataLabels.LabelValueVisible = True
chart.Series[0].DataLabels.PercentValueVisible = True
# Save file
presentation.SaveToFile("PieChartExample.pptx", FileFormat.Pptx2013)
presentation.Dispose()
Result Preview:
Code Analysis
The AppendChartInit method is used to add a chart at a specified position, where the first parameter specifies the chart type and the second parameter defines the rectangular area.
Data is bound through the ChartData two-dimensional array, where [row, column] indices correspond to cell positions. SeriesLabel specifies the source of series names, CategoryLabels sets the category label range, and Values binds the actual numerical data.
Each data point is individually configured through ChartDataPoint objects, allowing precise control over colors and styles. The DataLabels property controls label display content, and displaying both values and percentages provides more complete information.
Creating Donut Charts
Donut charts are a variant of pie charts with a hollow center forming a ring structure. They offer a more modern visual appearance and are suitable for displaying comparative data such as market share.
Implementation Method
The creation process for donut charts is similar to pie charts, with the main differences being the chart type and additional ring size settings.
from spire.presentation.common import *
from spire.presentation import *
# Create presentation document
presentation = Presentation()
rect = RectangleF.FromLTRB(80, 100, 630, 420)
# Add donut chart
chart = presentation.Slides[0].Shapes.AppendChartInit(ChartType.Doughnut, rect, False)
# Set title
chart.ChartTitle.TextProperties.Text = "Market Share by Country"
chart.ChartTitle.TextProperties.IsCentered = True
chart.ChartTitle.Height = 30
# Define data
countries = ["Cuba", "Mexico", "France", "Germany"]
sales = [1800, 3000, 5100, 6200]
# Write data
chart.ChartData[0, 0].Text = "Country"
chart.ChartData[0, 1].Text = "Sales"
for i in range(len(countries)):
chart.ChartData[i + 1, 0].Text = countries[i]
chart.ChartData[i + 1, 1].NumberValue = sales[i]
# Bind data series
chart.Series.SeriesLabel = chart.ChartData["B1", "B1"]
chart.Categories.CategoryLabels = chart.ChartData["A2", "A5"]
chart.Series[0].Values = chart.ChartData["B2", "B5"]
# Add data points and set colors
for i in range(len(chart.Series[0].Values)):
cdp = ChartDataPoint(chart.Series[0])
cdp.Index = i
chart.Series[0].DataPoints.Add(cdp)
chart.Series[0].DataPoints[0].Fill.FillType = FillFormatType.Solid
chart.Series[0].DataPoints[0].Fill.SolidColor.Color = Color.get_LightBlue()
chart.Series[0].DataPoints[1].Fill.FillType = FillFormatType.Solid
chart.Series[0].DataPoints[1].Fill.SolidColor.Color = Color.get_MediumPurple()
chart.Series[0].DataPoints[2].Fill.FillType = FillFormatType.Solid
chart.Series[0].DataPoints[2].Fill.SolidColor.Color = Color.get_DarkGray()
chart.Series[0].DataPoints[3].Fill.FillType = FillFormatType.Solid
chart.Series[0].DataPoints[3].Fill.SolidColor.Color = Color.get_DarkOrange()
# Display labels
chart.Series[0].DataLabels.LabelValueVisible = True
chart.Series[0].DataLabels.PercentValueVisible = True
# Set donut hole size (between 0-90)
chart.Series[0].DoughnutHoleSize = 60
# Save file
presentation.SaveToFile("DonutChartExample.pptx", FileFormat.Pptx2013)
presentation.Dispose()
Result Preview:
Key Features
The DoughnutHoleSize property controls the size of the hollow center area in the donut chart, with values ranging from 0 to 90. Larger values result in a larger center hole and thinner ring. The default value is typically between 50-60, achieving a balance between aesthetics and readability.
The data binding method for donut charts is identical to pie charts, allowing reuse of the same data processing logic.
Advanced Customization Techniques
Dynamic Color Assignment
In practical applications, colors may need to be dynamically assigned based on data volume. A predefined color list can be used with cyclic application:
# Predefined color list
colors = [
Color.get_LightBlue(),
Color.get_MediumPurple(),
Color.get_LightPink(),
Color.get_RosyBrown(),
Color.get_DarkOrange(),
Color.get_DarkGray()
]
# Cyclically apply colors
for i in range(len(chart.Series[0].Values)):
cdp = ChartDataPoint(chart.Series[0])
cdp.Index = i
chart.Series[0].DataPoints.Add(cdp)
chart.Series[0].DataPoints[i].Fill.FillType = FillFormatType.Solid
chart.Series[0].DataPoints[i].Fill.SolidColor.Color = colors[i % len(colors)]
This approach is suitable for scenarios with uncertain numbers of data points, ensuring each data point has an appropriate color.
Label Position Adjustment
Data label positions can be further customized through the DataLabels property:
# Set label display position
chart.Series[0].DataLabels.Position = LabelPositionType.OutsideEnd
# Display only percentages
chart.Series[0].DataLabels.LabelValueVisible = False
chart.Series[0].DataLabels.PercentValueVisible = True
# Customize label format
chart.Series[0].DataLabels.NumberFormat = "0.0%"
The LabelPositionType enumeration provides multiple position options, such as OutsideEnd, InsideEnd, Center, etc. The most suitable position can be selected based on chart layout.
Chart Background Configuration
To enhance visual appeal, backgrounds can be added to slides:
# Set background image
image_file = "background.png"
bg_rect = RectangleF.FromLTRB(0, 0, presentation.SlideSize.Size.Width,
presentation.SlideSize.Size.Height)
presentation.Slides[0].Shapes.AppendEmbedImageByPath(
ShapeType.Rectangle, image_file, bg_rect)
presentation.Slides[0].Shapes[0].Line.FillFormat.SolidFillColor.Color = Color.get_FloralWhite()
Background images should coordinate with chart colors to avoid interfering with data readability.
Practical Recommendations
Choose Appropriate Chart Types: Pie charts are suitable for displaying proportional relationships among 5-7 categories; too many categories reduce readability. Donut charts offer a more modern visual appearance, and the center area can be used to place total numbers or explanatory text.
Color Coordination Principles: Use contrasting colors to distinguish different data points, avoiding overly similar tones. Consider accessibility for color-blind users and validate color schemes using online tools.
Label Clarity: Displaying both values and percentages provides complete information, but if space is limited, show only percentages and note the total in the legend.
Data Sorting: Arrange data in descending order, displaying from the largest share clockwise, which aligns with reading habits and facilitates quick identification of major contributors.
Summary
Through Spire.Presentation for Python, pie charts and donut charts can be flexibly created and customized in PowerPoint. Core APIs include AppendChartInit for adding charts, ChartData for data binding, DataPoints for color customization, and DataLabels for label control.
These techniques can be applied to various business scenarios such as sales analysis, market research, and budget allocation, helping transform complex data into intuitive visual presentations. Combined with dynamic data sources, automated report generation can be achieved, significantly improving work efficiency.



Top comments (0)