Pie charts are a common way to represent the composition of a whole divided into parts. They are useful for visualizing data in categories, showing proportions, and illustrating percentages.
Matplotlib makes it easy to create and customize pie charts using the pie function.
In this tutorial, we’ll explore how to create and customize pie charts in Matplotlib with examples covering the basics, adding labels and percentages, creating exploded pie charts, using multiple colors, creating donut charts, and more.
1. Basic Pie Chart
A simple pie chart can be created using the pie function in Matplotlib. It requires a list of values representing the sizes of each slice.
import matplotlib.pyplot as plt # Sample data sizes = [25, 35, 20, 10, 10] labels = ['Category A', 'Category B', 'Category C', 'Category D', 'Category E'] # Create a basic pie chart plt.figure(figsize=(8, 8)) plt.pie(sizes, labels=labels) plt.title("Basic Pie Chart") plt.show()
In this example:
- sizes contains the values for each category, determining the relative size of each slice.
- labels=labels assigns labels to each slice.
2. Adding Colors and Starting Angle
You can add colors to each slice by passing a list of colors, and you can set the starting angle to rotate the chart.
# Custom colors and starting angle colors = ['lightblue', 'orange', 'green', 'purple', 'red'] plt.figure(figsize=(8, 8)) plt.pie(sizes, labels=labels, colors=colors, startangle=90) plt.title("Pie Chart with Custom Colors and Starting Angle") plt.show()
In this example:
- colors=colors assigns specific colors to each slice.
- startangle=90 rotates the chart so that it starts at 90 degrees (the top of the circle).
3. Adding Percentage Labels to Slices
You can use the autopct parameter to automatically display the percentage of each slice.
# Pie chart with percentage labels plt.figure(figsize=(8, 8)) plt.pie(sizes, labels=labels, colors=colors, startangle=90, autopct='%1.1f%%') plt.title("Pie Chart with Percentage Labels") plt.show()
In this example:
- autopct='%1.1f%%' displays the percentage with one decimal place for each slice.
4. Creating an Exploded Pie Chart
You can create an exploded pie chart by pulling one or more slices away from the center using the explode parameter.
# Explode one slice explode = (0, 0.1, 0, 0, 0) # Only "explode" the second slice plt.figure(figsize=(8, 8)) plt.pie(sizes, labels=labels, colors=colors, startangle=90, autopct='%1.1f%%', explode=explode) plt.title("Exploded Pie Chart") plt.show()
In this example:
- explode=(0, 0.1, 0, 0, 0) pulls the second slice (Category B) out from the center. Each position in the tuple corresponds to a slice, with values representing the distance from the center.
5. Adding a Shadow and Customizing the Edge
You can add a shadow to the chart to give it a 3D effect and customize the edge color of each slice.
# Pie chart with shadow and edge color plt.figure(figsize=(8, 8)) plt.pie(sizes, labels=labels, colors=colors, startangle=90, autopct='%1.1f%%', shadow=True, wedgeprops={'edgecolor': 'black'}) plt.title("Pie Chart with Shadow and Edge Color") plt.show()
In this example:
- shadow=True adds a shadow effect to the chart.
- wedgeprops={‘edgecolor': ‘black'} adds a black edge around each slice.
6. Pie Chart with Variable Slice Radius (Wedge Shape)
The radius of the pie chart can be adjusted to change its overall size. You can also use a wedge shape by setting the wedgeprops for different radii.
# Pie chart with variable slice radius plt.figure(figsize=(8, 8)) plt.pie(sizes, labels=labels, colors=colors, startangle=90, autopct='%1.1f%%', radius=1.2) plt.title("Pie Chart with Increased Radius") plt.show()
In this example:
- radius=1.2 increases the size of the pie chart.
7. Donut Chart (Pie Chart with a Hole)
A donut chart is a variation of a pie chart with a hole in the center. This can be achieved by setting a wedgeprops parameter with a smaller radius for the center.
# Donut chart plt.figure(figsize=(8, 8)) plt.pie(sizes, labels=labels, colors=colors, startangle=90, autopct='%1.1f%%', wedgeprops={'width': 0.3, 'edgecolor': 'black'}) plt.title("Donut Chart") plt.show()
In this example:
- wedgeprops={‘width': 0.3} creates a hole in the center, making it a donut chart. The width parameter controls the thickness of the ring.
8. Multiple Layered Donut Chart
You can create a multi-layered donut chart by plotting multiple pie charts with decreasing radii.
# Data for layered donut chart sizes_inner = [40, 30, 20, 10] sizes_outer = [20, 10, 5, 5, 15, 20, 10, 15] plt.figure(figsize=(8, 8)) # Outer ring plt.pie(sizes_outer, radius=1.3, colors=colors * 2, startangle=90, wedgeprops=dict(width=0.3, edgecolor='white')) # Inner ring plt.pie(sizes_inner, radius=1.0, colors=colors, startangle=90, wedgeprops=dict(width=0.3, edgecolor='white')) plt.title("Layered Donut Chart") plt.show()
In this example:
- Two pie charts are plotted with different radius values and width=0.3 to make them look like concentric rings.
9. Pie Chart with Legend Outside
You can place the legend outside the chart to avoid overlap with the slices, especially when there are many categories.
# Pie chart with legend outside plt.figure(figsize=(8, 8)) plt.pie(sizes, labels=labels, colors=colors, startangle=90, autopct='%1.1f%%') plt.legend(loc="center left", bbox_to_anchor=(1, 0.5)) plt.title("Pie Chart with Legend Outside") plt.show()
In this example:
- plt.legend(loc=”center left”, bbox_to_anchor=(1, 0.5)) positions the legend to the left of the pie chart, avoiding overlap.
10. Pie Chart with Percentage and Absolute Values
You can display both the percentage and absolute values in each slice by using a custom function with autopct.
# Function to display percentage and absolute values def absolute_value(val): total = sum(sizes) absolute = int(val/100 * total) return f'{val:.1f}%\n({absolute})' # Pie chart with percentage and absolute values plt.figure(figsize=(8, 8)) plt.pie(sizes, labels=labels, colors=colors, startangle=90, autopct=absolute_value) plt.title("Pie Chart with Percentage and Absolute Values") plt.show()
In this example:
- The absolute_value function calculates the absolute value for each slice and displays it along with the percentage.
11. Exploding Multiple Slices in a Pie Chart
You can explode multiple slices by specifying values for each slice in the explode parameter.
# Explode multiple slices explode = (0.1, 0.1, 0, 0, 0.1) # Explode selected slices plt.figure(figsize=(8, 8)) plt.pie(sizes, labels=labels, colors=colors, startangle=90, autopct='%1.1f%%', explode=explode) plt.title("Pie Chart with Multiple Exploded Slices") plt.show()
In this example:
- explode=(0.1, 0.1, 0, 0, 0.1) explodes three slices (A, B, and E) by setting non-zero values.
12. Using Subplots to Compare Multiple Pie Charts
You can use subplots to display multiple pie charts side by side for comparison.
# Data for subplots sizes_1 = [25, 30, 20, 25] sizes_2 = [10, 20, 30, 40] labels = ['Category A', 'Category B', 'Category C', 'Category D'] fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 6)) # First pie chart ax1.pie(sizes_1, labels=labels, autopct='%1.1f%%', startangle=90) ax1 .set_title("Pie Chart 1") # Second pie chart ax2.pie(sizes_2, labels=labels, autopct='%1.1f%%', startangle=90, colors=colors) ax2.set_title("Pie Chart 2") plt.suptitle("Comparison of Multiple Pie Charts") plt.show()
In this example:
- plt.subplots(1, 2) creates two side-by-side pie charts, allowing for easy comparison.
Summary
In this tutorial, we covered how to create and customize pie charts in Matplotlib:
- Basic Pie Chart for displaying categorical proportions.
- Adding Colors and Starting Angle to control aesthetics.
- Adding Percentage Labels to show proportions.
- Exploded Pie Chart to highlight specific slices.
- Adding Shadow and Edge Customization for a 3D effect.
- Variable Slice Radius to adjust chart size.
- Donut Chart for a pie chart with a hole.
- Layered Donut Chart for multiple concentric rings.
- Legend Outside to prevent overlap with slices.
- Percentage and Absolute Values in each slice.
- Exploding Multiple Slices for emphasis.
- Using Subplots for comparing multiple pie charts.
These examples demonstrate the versatility of Matplotlib’s pie function, allowing you to create effective and visually appealing pie charts tailored to your data visualization needs.