How to replace auto-labelled relative values by absolute values in Matplotlib?

In Matplotlib pie charts, auto-labelled values show percentages by default. To display absolute values instead, we can use a custom autopct function with lambda expressions.

Understanding the Problem

By default, Matplotlib pie charts show percentages. When you have actual data values like [5, 3, 4, 1], the chart displays percentages (38%, 23%, 31%, 8%) instead of the original values.

Solution Using Lambda Function

Use autopct=lambda p: '{:.0f}'.format(p * total / 100) to convert percentages back to absolute values ?

import matplotlib.pyplot as plt

# Configure figure size
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

# Data for pie chart
labels = ('Read', 'Eat', 'Sleep', 'Repeat')
fracs = [5, 3, 4, 1]
total = sum(fracs)
explode = (0, 0.05, 0, 0)

# Create pie chart with absolute values
plt.pie(fracs, explode=explode, labels=labels,
        autopct=lambda p: '{:.0f}'.format(p * total / 100),
        shadow=True, startangle=90)

plt.title("Daily Activities (Absolute Values)")
plt.show()

How It Works

The autopct parameter accepts a lambda function where:

  • p represents the percentage value for each slice
  • p * total / 100 converts percentage back to absolute value
  • '{:.0f}'.format() formats the result as a whole number

Alternative Approaches

Using a Regular Function

import matplotlib.pyplot as plt

def make_absolute(pct, values):
    absolute = int(round(pct/100. * sum(values)))
    return f'{absolute}'

data = [5, 3, 4, 1]
labels = ['Read', 'Eat', 'Sleep', 'Repeat']

plt.pie(data, labels=labels, 
        autopct=lambda pct: make_absolute(pct, data),
        startangle=90)

plt.title("Using Custom Function")
plt.show()

Showing Both Percentage and Absolute

import matplotlib.pyplot as plt

data = [5, 3, 4, 1]
labels = ['Read', 'Eat', 'Sleep', 'Repeat']
total = sum(data)

plt.pie(data, labels=labels,
        autopct=lambda p: f'{p:.1f}%\n({int(p * total / 100)})',
        startangle=90)

plt.title("Both Percentage and Absolute Values")
plt.show()

Key Points

  • Calculate total = sum(fracs) before creating the pie chart
  • Use p * total / 100 to convert percentage to absolute value
  • Format the output using '{:.0f}'.format() for whole numbers
  • The lambda function receives the percentage value automatically

Conclusion

Use autopct=lambda p: '{:.0f}'.format(p * total / 100) to display absolute values instead of percentages in Matplotlib pie charts. This approach converts the automatic percentage values back to the original data values for better clarity.

Updated on: 2026-03-25T23:00:20+05:30

825 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements