Matplotlib - Pie Chart
Matplotlib - Pie Charts
Section titled “Matplotlib - Pie Charts”A Pie Chart displays a single series of data as slices of a circle, where each slice’s size (angle) is proportional to its value relative to the sum of all items. They are used to show the composition of a whole.
Note: While visually simple, pie charts can be misleading, especially when comparing similar-sized slices or many categories. Bar charts are often a better alternative for comparing quantities. Use pie charts primarily when showing part-to-whole relationships for a small number of categories.
Creating a Pie Chart
Section titled “Creating a Pie Chart”The ax.pie() method (object-oriented API) generates a pie chart.
Key Parameters for ax.pie():
Section titled “Key Parameters for ax.pie():”| Parameter | Description |
|---|---|
x | A 1D array-like object containing the data values (wedge sizes). Matplotlib automatically calculates percentages. |
labels | A list of strings providing labels for each wedge. |
colors | A sequence of colors for the wedges. If None, uses the default color cycle. |
autopct | A string or function used to format the numeric value displayed on each wedge. Common format: '%1.1f%%' (shows percentage with one decimal place). |
explode | A tuple or list of the same length as x, specifying the fraction of the radius to offset each wedge. Use this to emphasize a slice (e.g., (0, 0.1, 0, 0) offsets the second slice). |
startangle | Rotates the start of the first slice counterclockwise from the x-axis (default is 0 degrees). |
shadow | If True, draws a shadow beneath the pie. |
pctdistance | Ratio of the radius at which the autopct text is drawn (default 0.6). |
labeldistance | Ratio of the radius at which the labels are drawn (default 1.1). |
Example: Course Enrollment
Section titled “Example: Course Enrollment”Let’s visualize the distribution of students across different programming language courses.
import matplotlib.pyplot as pltimport numpy as np
# Data: Programming languages and number of studentslanguages = ['C', 'C++', 'Java', 'Python', 'PHP']students = [23, 17, 35, 29, 12]
# Create Figure and Axesfig, ax = plt.subplots(figsize=(7, 7)) # Square figure looks better for pies
# Explode the 'Python' slice slightlyexplode = (0, 0, 0, 0.1, 0) # 0.1 indicates 10% radius offset
# Create the pie chartwedges, texts, autotexts = ax.pie( students, labels=languages, autopct='%1.1f%%', # Format for percentage display startangle=90, # Start first slice at 90 degrees (top) explode=explode, # Apply the explode effect shadow=True, # Add a shadow colors=['gold', 'lightcoral', 'lightskyblue', 'lightgreen', 'yellowgreen'] # Optional custom colors)
# Ensure the pie is drawn as a circleax.axis('equal')
# Add a titleax.set_title('Student Enrollment by Programming Language')
# Improve layoutplt.tight_layout()plt.show()This code generates a pie chart showing the proportion of students enrolled in each language. The ‘Python’ slice is slightly offset (‘exploded’) for emphasis. Percentages are displayed on each slice, labels identify the languages, a shadow effect is added, and ax.axis('equal') ensures the chart is circular rather than elliptical.
The ax.pie function returns three lists: wedges (the Patch objects for slices), texts (the label Text objects), and autotexts (the numeric label Text objects), which you could use for further customization if needed.