Conditional removal of labels in Matplotlib pie chart

To remove labels from a Matplotlib pie chart based on a condition, you can use a lambda function in the autopct parameter. This technique is useful when you want to display percentage labels only for slices that meet certain criteria, such as being above a specific threshold.

Steps to Conditionally Remove Labels

  • Set the figure size and adjust the padding between and around the subplots
  • Create a Pandas DataFrame with your data
  • Plot a pie chart using pie() method with conditional removal of labels
  • Use a lambda function in autopct to show labels only when conditions are met
  • Display the figure using show() method

Example

Here's how to create a pie chart that shows percentage labels only when the value is greater than 25% ?

import pandas as pd
from matplotlib import pyplot as plt

# Set the figure size
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True

# Create a Pandas DataFrame
df = pd.DataFrame({
    'activities': ['sleep', 'exercise', 'work', 'study'],
    'hours': [8, 1, 9, 4]
})

# Pie chart with conditional removal of labels
df.set_index('activities').plot.pie(
    y='hours', 
    legend=False, 
    autopct=lambda p: format(p, '.2f') + '%' if p > 25 else ''
)

plt.title('Daily Activities Distribution')
plt.ylabel('')  # Remove default ylabel
plt.show()

Output

The pie chart displays percentage labels only for slices representing more than 25% of the total. In this example, only "sleep" (36.36%) and "work" (40.91%) show labels, while "exercise" and "study" have no percentage labels since they represent less than 25% each.

How It Works

The autopct parameter accepts a lambda function that receives the percentage value for each slice. The condition p > 25 checks if the percentage is greater than 25. If true, it formats and returns the percentage; if false, it returns an empty string, effectively hiding the label.

Alternative Approaches

You can also conditionally remove slice labels (not just percentages) ?

import pandas as pd
from matplotlib import pyplot as plt

df = pd.DataFrame({
    'activities': ['sleep', 'exercise', 'work', 'study'],
    'hours': [8, 1, 9, 4]
})

# Calculate percentages
percentages = (df['hours'] / df['hours'].sum()) * 100

# Create labels conditionally
labels = [activity if pct > 25 else '' for activity, pct in zip(df['activities'], percentages)]

plt.figure(figsize=(7, 4))
plt.pie(df['hours'], labels=labels, autopct='%1.1f%%')
plt.title('Daily Activities with Conditional Labels')
plt.show()

Conclusion

Use lambda functions in autopct to conditionally display percentage labels in pie charts. This approach helps reduce clutter by showing labels only for significant slices that meet your specified criteria.

Updated on: 2026-03-26T02:28:17+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements