Matplotlib Pie Chart Autopct to Format Percentages

I have found that a pie chart is only as good as its labels. Without clear percentage markers, your audience has to guess the proportions of your data.

The autopct parameter in the Matplotlib pie() function is the primary tool we use to display these percentages automatically. It calculates the share of each slice and formats it into a readable string.

In this tutorial, I will show you exactly how I use the Matplotlib pie chart autopct parameter to create professional-grade charts in Python. I’ll use real-world data, such as market shares of American tech companies and demographic statistics, to make things clear.

What is the Matplotlib Pie Chart Autopct Parameter?

When I first started using Matplotlib in Python, I struggled to get the percentage labels to show up on my charts. I eventually realized that the autopct (short for automatic percentage) parameter is the secret sauce.

It accepts either a format string or a function. This flexibility allows me to decide if I want to show one decimal place, two decimal places, or even combine the percentage with the raw data values.

Method 1: Use Basic String Formatting with Autopct

The most common way I use the Matplotlib pie chart autopct parameter is through string formatting. This method is quick and works perfectly for most Python data visualization tasks.

For this example, let’s look at a hypothetical breakdown of popular smartphone operating systems used in the USA.

import matplotlib.pyplot as plt

# Data representing OS market share in a US city
labels = ['iOS', 'Android', 'Others']
sizes = [55.8, 43.2, 1.0]
colors = ['#f5f5f7', '#3ddc84', '#9e9e9e']

# I use %1.1f%% to show one decimal place
plt.figure(figsize=(8, 6))
plt.pie(sizes, labels=labels, autopct='%1.1f%%', startangle=140, colors=colors)

plt.title('Smartphone OS Market Share in the USA (Python Matplotlib)')
plt.show()

You can see the output in the screenshot below.

Matplotlib Pie Chart Autopct

In the code above, I used the string format %1.1f%%. The %1.1f tells Python to format the number as a float with one decimal point. The trailing %% is how I tell Matplotlib to literally print a “%” sign after the number.

Method 2: Format to Zero or Multiple Decimal Places

Sometimes, a single decimal point isn’t enough, or it’s too much. If I am presenting to executives at a US retail firm, they often prefer whole numbers. If I am doing scientific Python research, I might need three decimal places.

Here is how I adjust the precision using the Matplotlib pie chart autopct syntax:

  • Zero decimal places: Use ‘%1.0f%%’
  • Two decimal places: Use ‘%1.2f%%’

Let’s apply this to a breakdown of US Household Expenses.

import matplotlib.pyplot as plt

# US Household Expense Categories
categories = ['Housing', 'Transportation', 'Food', 'Healthcare', 'Insurance']
spending = [3500, 1200, 900, 600, 500]

# Creating the Python pie chart
fig, ax = plt.subplots()
ax.pie(spending, labels=categories, autopct='%1.0f%%', shadow=True)

plt.title('Average US Monthly Household Spending (Python)')
plt.show()

You can see the output in the screenshot below.

Matplotlib Pie Chart Autopct Python

By changing the format string to '%1.0f%%', I ensure the chart looks clean and uncluttered by rounding the values to the nearest whole percentage.

Method 3: Use a Lambda Function for Custom Autopct Labels

I often encounter situations where I need to show both the percentage and the actual value (like the dollar amount or count). A simple string won’t work here.

In these cases, I pass a Python lambda function to the autopct parameter. This function receives the calculated percentage as an input.

Here is a script I wrote to visualize the distribution of electric vehicles (EVs) in a US parking garage.

import matplotlib.pyplot as plt

# Data: Number of vehicles
vehicles = [25, 15, 10, 50]
labels = ['Tesla', 'Ford', 'Chevrolet', 'Other ICE']

def make_autopct(values):
    def my_autopct(pct):
        total = sum(values)
        val = int(round(pct*total/100.0))
        return '{p:.1f}%\n({v:d} cars)'.format(p=pct, v=val)
    return my_autopct

plt.figure(figsize=(10, 7))
plt.pie(vehicles, labels=labels, autopct=make_autopct(vehicles), colors=['red', 'blue', 'green', 'gray'])

plt.title('US Parking Lot Vehicle Distribution (Python Example)')
plt.show()

You can see the output in the screenshot below.

Matplotlib Pie Chart Autopct to Format Percentages

In this advanced Python approach, the nested function calculates the absolute number of cars based on the percentage provided by Matplotlib. I then return a formatted string that includes both values.

Method 4: Change the Distance of Autopct Labels

One problem I frequently face is labels overlapping or being too close to the center of the pie chart. To fix this, I use the pctdistance parameter alongside autopct.

If I set pctdistance=0.85, the labels move further away from the center toward the edge of the slice.

import matplotlib.pyplot as plt

# US State Population Sample (Millions)
states = ['California', 'Texas', 'Florida', 'New York']
pop = [39, 30, 22, 19]

plt.pie(pop, labels=states, autopct='%1.1f%%', pctdistance=0.8)

plt.title('Population Distribution of Selected US States')
plt.show()

You can see the output in the screenshot below.

Pie Chart Autopct Format Percentages in Matplotlib

I find that a pctdistance between 0.7 and 0.85 usually provides the best readability for Python-generated charts.

Method 5: Style Autopct Text Labels

Colors and font sizes matter for accessibility. When I create Python pie charts for US-based websites, I make sure the percentage text is legible against the slice color.

I use the textprops argument to modify the style of the autopct output.

import matplotlib.pyplot as plt

# Revenue share for a US Tech Company
labels = ['Services', 'Hardware', 'Software', 'Licensing']
revenue = [45, 30, 15, 10]

plt.pie(revenue, labels=labels, autopct='%1.1f%%', 
        textprops={'color':"w", 'weight':'bold', 'fontsize':12})

plt.title('Revenue Breakdown (Styled Autopct Labels)')
plt.show()

Setting the color to ‘w’ (white) and the weight to ‘bold’ makes the percentages pop, especially if I am using a dark theme or vibrant slice colors.

Common Mistakes When Using Autopct in Python

During my time working with Matplotlib, I have seen beginners make a few consistent errors:

  1. Forgetting the double percent sign: If you use ‘%1.1f%’, Python will throw an error. You must use %% to escape the character.
  2. Mismatched data types: Ensure your data consists of numeric values (integers or floats). If you pass strings to the pie() function, the autopct calculation will fail.
  3. Crowded Charts: If you have 20 slices, showing autopct on every slice makes the chart unreadable. In those cases, I usually group smaller values into an “Other” category.

I hope you find this tutorial on the Matplotlib pie chart autopct parameter useful. Using these formatting techniques in your Python scripts will make your data visualizations much more professional and easier for your audience to interpret.

You may also read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.