Matplotlib Pie Charts
plt.pie() draws each value in a dataset as a proportional slice of a circle, making it well suited for showing how parts contribute to a whole.
What a Pie Chart Is For
A pie chart shows how a total is split into parts, such as market share by company or a budget split across expense categories. It works best with a small number of slices — beyond five or six categories, the slices become hard to compare by eye, and a bar chart usually communicates the same information more clearly.
Basic Pie Chart
plt.pie(values) draws one slice per value, sized proportionally to that value's share of the total. Pass labels to name each slice.
Example
import matplotlib.pyplot as plt
browsers = ["Chrome", "Safari", "Edge", "Firefox", "Other"]
market_share = [63, 19, 8, 6, 4]
plt.pie(market_share, labels=browsers)
plt.title("Browser market share")
plt.show()Showing Percentages with autopct
The autopct argument prints a value directly on each slice, computed from that slice's share of the total. It takes a printf-style format string: "%1.1f%%" prints the percentage with one digit after the decimal point, followed by a literal percent sign.
Example
import matplotlib.pyplot as plt
expenses = ["Housing", "Food", "Transport", "Entertainment"]
monthly_spend = [1200, 450, 300, 150]
plt.pie(monthly_spend, labels=expenses, autopct="%1.1f%%", startangle=90)
plt.title("Monthly expense breakdown")
plt.show()The explode argument accepts a list matching the number of slices, where each number is how far that slice should be pushed out from the center — 0 keeps a slice in place. Combine this with plt.legend() when slice labels are too crowded to print directly next to small slices.
Example
import matplotlib.pyplot as plt
teams = ["Team A", "Team B", "Team C", "Team D"]
points_scored = [28, 35, 19, 42]
explode = [0, 0, 0, 0.1]
colors = ["#4C72B0", "#DD8452", "#55A868", "#C44E52"]
plt.pie(points_scored, labels=teams, explode=explode, colors=colors,
autopct="%1.0f%%", shadow=True)
plt.legend(title="Teams")
plt.show()- labels names each slice; without it, slices are drawn with no text at all.
- autopct formats and prints a value on each slice, most often a percentage.
- explode shifts one or more slices outward to draw attention to them.
- colors sets an explicit color per slice, overriding Matplotlib's default color cycle.
- startangle rotates the whole chart so the first slice does not have to start at the 3 o'clock position.
Exercise: Matplotlib Pie Charts
Do the values passed to plt.pie() need to sum to 100?