Matplotlib pie() Function


Matplotlib 参考文档Matplotlib Reference Documentation

pie()Used to draw pie charts, showing the proportional relationship of each part to the whole.

Pie charts are suitable for displaying the proportions of a small number of categories (usually within 5-8).

Function Definition

pyplot Interface

matplotlib.pyplot.pie(x, explode=None, labels=None, colors=None,
    autopct=None, pctdistance=0.6, shadow=False, labeldistance=1.1,
    startangle=0, radius=1, counterclock=True, wedgeprops=None,
    textprops=None, center=(0, 0), frame=False, rotatelabels=False, *,
    normalize=True, hatch=None, **kwargs)

Axes Interface

Axes.pie(x, explode=None, labels=None, colors=None, autopct=None,
    pctdistance=0.6, shadow=False, labeldistance=1.1, startangle=0,
    radius=1, counterclock=True, wedgeprops=None, textprops=None,
    center=(0, 0), frame=False, rotatelabels=False, *,
    normalize=True, hatch=None, **kwargs)

Parameter Description

ParameterTypeDescription
x1D array-likeThe value of each sector (required), automatically normalized.
explodearray-likeThe distance each sector is offset from the center; 0 means no offset.
labelslistLabel text for each sector.
colorslistColor of each sector.
autopctstr or callableAutomatically display percentages, e.g., '%1.1f%%' means one decimal place; None hides it.
pctdistancefloatDistance ratio of percentage text from the center, default 0.6.
shadowboolWhether to add a shadow effect.
labeldistancefloatDistance ratio of labels from the center, default 1.1.
startanglefloatStarting angle of the first sector (counterclockwise); 0 means starting from the 3 o'clock direction.
radiusfloatPie chart radius, default 1.
counterclockboolSector direction: True is counterclockwise (default), False is clockwise.
wedgepropsdictParameters passed to each sector (Wedge), e.g., {'edgecolor':'white', 'linewidth':1}
textpropsdictParameters passed to text, e.g., {'fontsize':12, 'color':'gray'}
centertuplePie chart center coordinates, default (0, 0).
normalizeboolWhether to normalize x so the total is 1, default True.

pie() returns three lists:(patches, texts, autotexts)patches are the sector objects, texts are the label texts, and autotexts are the percentage texts.


Usage Examples

Example 1: Basic Pie Chart

Example

import matplotlib.pyplot as plt

# Data
sizes = [30, 25, 20, 15, 10]
labels = ['Python', 'Java', 'JavaScript', 'C++', 'Go']
colors = ['#3498db', '#e74c3c', '#f39c12', '#2E7DCC', '#9b59b6']

fig, ax = plt.subplots(layout='constrained')

# Draw pie chart
ax.pie(sizes, labels=labels, colors=colors,
       autopct='%1.1f%%',         # Display percentages, keeping one decimal place
       startangle=90,             # Start from the 12 o'clock direction
       wedgeprops={'edgecolor': 'white', 'linewidth': 1})

ax.set_title('Programming Language Usage')
plt.show()

Example 2: Highlighting a Specific Sector (explode)

Example

import matplotlib.pyplot as plt

sizes = [35, 25, 20, 12, 8]
labels = ['Search', 'Social', 'Direct', 'Email', 'Referral']
explode = (0.1, 0, 0, 0, 0)  # Offset the first sector (Search) by 0.1

fig, ax = plt.subplots(layout='constrained')

wedges, texts, autotexts = ax.pie(
    sizes, labels=labels, explode=explode,
    autopct='%1.1f%%', startangle=90,
    colors=['#2E7DCC', '#3498db', '#9b59b6', '#f39c12', '#e74c3c'],
    wedgeprops={'edgecolor': 'white', 'linewidth': 1},
    textprops={'fontsize': 11})

# Modify the color of the percentage text
for autotext in autotexts:
    autotext.set_color('white')
    autotext.set_fontweight('bold')

ax.set_title('Website Traffic Sources', fontsize=14)
plt.show()

Example 3: Donut Chart (Doughnut Chart)

Example

import matplotlib.pyplot as plt

sizes = [40, 30, 20, 10]
labels = ['Chrome (40%)', 'Safari (30%)', 'Firefox (20%)', 'Other (10%)']

fig, ax = plt.subplots(layout='constrained')

# Use wedgeprops to set width to create a donut chart
wedges, texts = ax.pie(
    sizes, labels=labels,
    startangle=90,
    colors=['#4285F4', '#346EA8', '#FBBC05', '#EA4335'],
    wedgeprops={'width': 0.4,      # Sector width (0~1); if <1, it becomes a donut
                'edgecolor': 'white', 'linewidth': 2})

ax.set_title('Browser Market Share (Donut Chart)', fontsize=14)
plt.show()

Example 4: Multi-level Donut Chart

Example

import matplotlib.pyplot as plt

# Outer layer data and inner layer data
outer_sizes = [35, 30, 20, 15]
inner_sizes = [40, 30, 30]

outer_labels = ['Asia', 'Europe', 'America', 'Africa']
inner_labels = ['Mobile', 'Desktop', 'Tablet']

outer_colors = ['#FF6B6B', '#4ECDC4', '#45B7D1', '#71A0CE']
inner_colors = ['#FFE0B2', '#BBDEFB', '#C8D7E6']

fig, ax = plt.subplots(layout='constrained')

# Outer ring
ax.pie(outer_sizes, radius=1.3,
       labels=outer_labels,
       labeldistance=1.1,
       colors=outer_colors,
       wedgeprops={'width': 0.3, 'edgecolor': 'white', 'linewidth': 2})

# Inner ring
ax.pie(inner_sizes, radius=1.0,
       labels=inner_labels,
       labeldistance=0.75,
       colors=inner_colors,
       wedgeprops={'width': 0.3, 'edgecolor': 'white', 'linewidth': 2})

ax.set_title('Multi-level Donut Chart', fontsize=14)
plt.show()

FAQ

Pie Chart vs Bar Chart: When to Use Which?

Pie charts are suitable for showing proportions of up to 5-8 categories, allowing readers to intuitively grasp the share of the whole.

When there are too many categories (more than 8) or precise numerical comparison is needed, prefer a bar chart.

autopct Format Explanation?

'%1.1f%%'Means a floating-point number with a minimum total width of 1 digit and 1 decimal place, followed by%%(percent sign).

You can also pass a function, such asautopct=lambda pct: f'{pct:.1f}%'。


Matplotlib 参考文档Matplotlib Reference Documentation

Other Extensions