Pie Charts in Matplotlib
Learn how to create pie charts using Matplotlib in Python. Understand slices, percentages, labels, colours, exploded slices, donut charts and different customization options.
1. Learning Objectives
After completing this lesson, you will be able to:
- Understand what a pie chart is and where it is used.
- Create a basic pie chart using Matplotlib.
- Add labels and percentage values to pie charts.
- Change the starting angle and direction of slices.
- Highlight individual slices using the explode parameter.
- Customize colours, borders, text and shadows.
- Create donut charts using the pie chart function.
- Display legends and improve pie chart readability.
2. Introduction to Pie Charts
A pie chart is a circular statistical chart used to represent numerical data as parts of a whole. Each part of the circle is called a slice or sector.
The size of each slice represents its proportion of the total value. A larger value creates a larger slice, while a smaller value creates a smaller slice.
Real-Life Example
Suppose a company has a monthly budget of ₹50,000. The budget is divided into Rent, Food, Transport and Savings. A pie chart can show how much of the total budget is used by each category.
Conceptual diagram showing how a total value is divided into different pie chart slices.
3. Import Matplotlib
Before creating a pie chart, import the Matplotlib library. We commonly use the pyplot module to create charts.
import matplotlib.pyplot as plt
We use plt.pie() to create a pie chart and
plt.show() to display it.
4. Creating a Basic Pie Chart
The plt.pie() function creates a pie chart from
numerical values. Each value represents one slice of the chart.
Example
import matplotlib.pyplot as plt
values = [40, 30, 20, 10]
plt.pie(values)
plt.title("Basic Pie Chart")
plt.show()
Expected Output
Basic Pie Chart
A circular chart is displayed with four slices.
Slice 1 = 40
Slice 2 = 30
Slice 3 = 20
Slice 4 = 10
Total = 100
5. Adding Labels to Pie Charts
Labels help users understand what each slice represents.
Use the labels parameter to provide category names.
import matplotlib.pyplot as plt
values = [40, 30, 20, 10]
labels = ["Python", "Java", "C++", "JavaScript"]
plt.pie(values, labels=labels)
plt.title("Programming Language Popularity")
plt.show()
Expected Output
Programming Language Popularity
A pie chart displays four labelled slices:
Python : 40
Java : 30
C++ : 20
JavaScript : 10
Understanding labels
The labels list must contain the same number of items as the values list. Each label is connected to its corresponding slice.
6. Displaying Percentages with autopct
The autopct parameter displays percentage values
inside each slice. It accepts a formatting string or a
formatting function.
import matplotlib.pyplot as plt
values = [40, 30, 20, 10]
labels = ["Python", "Java", "C++", "JavaScript"]
plt.pie(
values,
labels=labels,
autopct="%1.1f%%"
)
plt.title("Programming Language Share")
plt.show()
Expected Output
Programming Language Share
Python 40.0%
Java 30.0%
C++ 20.0%
JavaScript 10.0%
%1.1f%% displays
one digit after the decimal point. For example, 25.5%.
Percentage Formatting Examples
| Format | Meaning | Example |
|---|---|---|
%1.0f%% |
Zero decimal places | 25% |
%1.1f%% |
One decimal place | 25.5% |
%1.2f%% |
Two decimal places | 25.55% |
7. Changing the Starting Angle with startangle
By default, Matplotlib starts drawing a pie chart from the
horizontal right side. The startangle parameter
rotates the starting position of the slices.
import matplotlib.pyplot as plt
values = [40, 30, 20, 10]
labels = ["Rent", "Food", "Transport", "Savings"]
plt.pie(
values,
labels=labels,
autopct="%1.1f%%",
startangle=90
)
plt.title("Monthly Budget Distribution")
plt.show()
Expected Output
Monthly Budget Distribution
A pie chart is displayed with the first slice
starting from an angle of 90 degrees.
The chart is rotated compared to the default
starting position.
startangle=90 when you
want the first slice to begin from the top of the chart.
8. Highlighting Slices with explode
The explode parameter separates selected slices
from the main pie chart. It is useful when you want to
highlight an important category.
import matplotlib.pyplot as plt
values = [40, 30, 20, 10]
labels = ["Rent", "Food", "Transport", "Savings"]
explode = (0.1, 0, 0, 0)
plt.pie(
values,
labels=labels,
explode=explode,
autopct="%1.1f%%",
startangle=90
)
plt.title("Budget with Highlighted Rent")
plt.show()
Expected Output
Budget with Highlighted Rent
Rent slice is separated slightly from the pie chart.
Food, Transport and Savings remain in their
normal positions.
The first value in explode controls the first
slice, the second value controls the second slice, and so on.
9. Customizing Pie Chart Colours
Use the colors parameter to assign different
colours to individual slices.
import matplotlib.pyplot as plt
values = [40, 30, 20, 10]
labels = ["Rent", "Food", "Transport", "Savings"]
colors = ["#2563eb", "#16a34a", "#f59e0b", "#a855f7"]
plt.pie(
values,
labels=labels,
colors=colors,
autopct="%1.1f%%"
)
plt.title("Monthly Budget Distribution")
plt.show()
Expected Output
Monthly Budget Distribution
Rent : Blue
Food : Green
Transport : Orange
Savings : Purple
Each category is displayed using its assigned colour.
Common Colour Options
| Colour | Hex Code | Common Use |
|---|---|---|
| Blue | #2563eb |
General category |
| Green | #16a34a |
Positive values |
| Orange | #f59e0b |
Important category |
| Purple | #a855f7 |
Additional category |
10. Adding Shadow to Pie Charts
The shadow parameter adds a shadow effect to
the pie chart. It can make the chart visually stand out.
import matplotlib.pyplot as plt
values = [45, 25, 20, 10]
labels = ["A", "B", "C", "D"]
plt.pie(
values,
labels=labels,
autopct="%1.1f%%",
shadow=True,
startangle=90
)
plt.title("Pie Chart with Shadow")
plt.show()
Expected Output
Pie Chart with Shadow
A pie chart is displayed with four labelled slices
and a shadow effect behind the chart.
11. Customizing Slice Borders with wedgeprops
The wedgeprops parameter allows you to customize
the appearance of pie chart slices, including their borders.
import matplotlib.pyplot as plt
values = [40, 30, 20, 10]
labels = ["Rent", "Food", "Travel", "Savings"]
plt.pie(
values,
labels=labels,
autopct="%1.1f%%",
wedgeprops={
"edgecolor": "white",
"linewidth": 2
}
)
plt.title("Pie Chart with White Borders")
plt.show()
Expected Output
Pie Chart with White Borders
Each slice has a white border.
The border width is 2 points.
Percentage values are displayed inside slices.
Common wedgeprops Options
| Property | Purpose |
|---|---|
edgecolor |
Sets the border colour of slices. |
linewidth |
Controls the border thickness. |
width |
Controls slice width and helps create donut charts. |
12. Creating a Donut Chart
A donut chart is a variation of a pie chart with a hollow
centre. In Matplotlib, we can create it by using the
width property inside wedgeprops.
import matplotlib.pyplot as plt
values = [40, 30, 20, 10]
labels = ["Rent", "Food", "Travel", "Savings"]
plt.pie(
values,
labels=labels,
autopct="%1.1f%%",
wedgeprops={"width": 0.4}
)
plt.title("Monthly Budget Donut Chart")
plt.show()
Expected Output
Monthly Budget Donut Chart
A circular chart is displayed with a hollow centre.
The chart contains four labelled segments.
Each segment displays its percentage value.
Conceptual illustration of a donut chart and its hollow centre.
13. Adding a Legend to a Pie Chart
A legend identifies the categories represented by different
colours. You can use plt.legend() to display
category names separately from the pie chart.
import matplotlib.pyplot as plt
values = [40, 30, 20, 10]
labels = ["Rent", "Food", "Travel", "Savings"]
plt.pie(
values,
autopct="%1.1f%%",
startangle=90
)
plt.legend(
labels,
title="Budget Categories",
loc="best"
)
plt.title("Budget Distribution with Legend")
plt.show()
Expected Output
Budget Distribution with Legend
A pie chart displays percentage values.
A separate legend identifies:
Rent, Food, Travel and Savings.
14. Maintaining a Circular Shape
A pie chart should normally appear circular rather than oval.
Use plt.axis("equal") to maintain an equal aspect
ratio when using pyplot.
import matplotlib.pyplot as plt
values = [35, 25, 20, 20]
labels = ["A", "B", "C", "D"]
plt.pie(
values,
labels=labels,
autopct="%1.1f%%"
)
plt.axis("equal")
plt.title("Equal Aspect Ratio Pie Chart")
plt.show()
Expected Output
Equal Aspect Ratio Pie Chart
The pie chart is displayed as a proper circle
instead of a stretched oval shape.
ax.set_aspect("equal").
15. Creating Pie Charts with the Object-Oriented API
Matplotlib also supports the object-oriented approach.
Instead of directly calling plt.pie(), create
a Figure and Axes object and call ax.pie().
import matplotlib.pyplot as plt
values = [40, 30, 20, 10]
labels = ["Python", "Java", "C++", "JavaScript"]
fig, ax = plt.subplots(figsize=(7, 5))
ax.pie(
values,
labels=labels,
autopct="%1.1f%%",
startangle=90
)
ax.set_title("Programming Language Distribution")
ax.set_aspect("equal")
plt.show()
Expected Output
Programming Language Distribution
A labelled pie chart is displayed.
Each category shows its percentage.
The chart maintains a circular shape.
Why use the Object-Oriented API?
It gives better control over individual charts and is especially useful when working with multiple subplots or complex figures.
16. Important Parameters of plt.pie()
The following table explains commonly used parameters of the Matplotlib pie chart function.
| Parameter | Description | Example |
|---|---|---|
x |
Numerical values for each slice. | [40, 30, 20] |
labels |
Names of the pie chart categories. | labels=names |
colors |
Colours assigned to slices. | colors=colors |
autopct |
Displays percentage values. | autopct="%1.1f%%" |
startangle |
Rotates the starting position. | startangle=90 |
explode |
Separates selected slices. | explode=(0.1, 0, 0) |
shadow |
Adds a shadow effect. | shadow=True |
counterclock |
Controls the direction of slices. | counterclock=False |
normalize |
Controls normalization of values. | normalize=True |
wedgeprops |
Customizes slice properties. | wedgeprops=props |
textprops |
Customizes text properties. | textprops=props |
pctdistance |
Controls percentage text distance from centre. | pctdistance=0.6 |
labeldistance |
Controls category label distance from centre. | labeldistance=1.1 |
17. Practical Example: Company Budget Distribution
Let's create a pie chart for a company that divides its monthly budget into four categories: Salaries, Rent, Marketing and Operations.
Complete Python Program
import matplotlib.pyplot as plt
categories = [
"Salaries",
"Rent",
"Marketing",
"Operations"
]
budget = [50000, 20000, 15000, 15000]
colors = [
"#2563eb",
"#16a34a",
"#f59e0b",
"#a855f7"
]
explode = (0.05, 0, 0, 0)
fig, ax = plt.subplots(figsize=(8, 6))
ax.pie(
budget,
labels=categories,
colors=colors,
autopct="%1.1f%%",
startangle=90,
explode=explode,
shadow=True,
wedgeprops={
"edgecolor": "white",
"linewidth": 2
}
)
ax.set_title("Company Monthly Budget Distribution")
ax.set_aspect("equal")
plt.show()
Expected Output
Company Monthly Budget Distribution
Salaries : ₹50,000 (50%)
Rent : ₹20,000 (20%)
Marketing : ₹15,000 (15%)
Operations : ₹15,000 (15%)
Total Budget : ₹1,00,000
The Salaries slice is slightly separated
from the remaining slices.
Understanding the Result
Salaries represent half of the company's monthly budget. Rent represents 20%, while Marketing and Operations represent 15% each. The chart makes it easy to understand how the total budget is distributed.
18. Best Practices for Pie Charts
- Use pie charts when showing parts of a whole.
- Keep the number of categories small.
- Use clear labels for every important category.
- Use percentage values when they improve understanding.
- Choose colours that are easy to distinguish.
- Use explode only to highlight important slices.
- Avoid unnecessary shadows and visual effects.
- Maintain a circular aspect ratio.
19. Common Mistakes and Solutions
| Common Mistake | Solution |
|---|---|
| Labels do not match the number of values. | Provide one label for each value. |
| Explode sequence has the wrong length. | Match explode values with the number of slices. |
| Pie chart looks stretched. | Use plt.axis("equal"). |
| Percentage values are difficult to read. | Adjust autopct formatting and text properties. |
| Too many categories are displayed. | Combine smaller categories or use a bar chart. |
| Colours are difficult to distinguish. | Choose a clear and contrasting colour palette. |
20. Practice Questions
Beginner Level
- What is a pie chart?
- Which function creates a pie chart in Matplotlib?
- What is the purpose of the labels parameter?
- How do you display percentage values?
- What is the use of startangle?
Intermediate Level
- Explain the explode parameter with an example.
- How can you customize pie chart colours?
- What is the purpose of wedgeprops?
- How do you create a donut chart?
- What is the difference between plt.pie() and ax.pie()?
Practical Tasks
- Create a pie chart showing student marks distribution.
- Create a pie chart showing monthly expenses.
- Highlight the largest slice using explode.
- Create a donut chart with percentage values.
- Create a company sales distribution chart with a legend.
Summary
A pie chart is a circular statistical chart used to represent different categories as parts of a whole. Each slice represents the proportion of a category in the total dataset.
Matplotlib provides the plt.pie() function to
create pie charts. The labels parameter adds category names,
while autopct displays percentage values inside the slices.
Parameters such as startangle, explode, colors and shadow help customize the appearance of a pie chart. The wedgeprops parameter can customize slice borders and can also be used to create donut charts.
The object-oriented approach provides additional control
through the Axes object and its ax.pie() method.
Pie charts are most useful when displaying a small number
of categories that represent parts of a total.