If you want to show the percentage value in the pie chart, then use the autopct
argument of the plt.pie()
method. The autopct
argument accepts a format string or a function.
If you specify the format string, then it must be enclosed within the %
sign.
Note: The labels will be displayed inside the wedges and will be according to the format string passed to the autopct
argument.
The following code will show you how to specify format string to the autopct argument.
import matplotlib.pyplot as plt data = [24, 6, 6, 36, 28] label = ['Natural Gas', 'Hydro', 'Nuclear', 'Oil', 'Coal'] plt.pie(data, labels=label, autopct='%1.1f%%', explode=[0,0,0,0.1,0], shadow=True, startangle=90) plt.title('World Energy Consumption') plt.axis('equal') plt.show()
Output
When you pass a function to the autopct argument, it must be a lambda function.
import matplotlib.pyplot as plt expenses = [500, 1000, 721, 200, 938, 100] labels = ['Rent', 'Gas', 'Food', 'Clothing', 'Car Payment', 'Misc'] def func(pct): return "{:1.1f}%".format(pct) plt.pie(expenses, labels=labels, autopct=lambda pct: func(pct), explode=[0,0,0,0,0.2,0], shadow=True) plt.title('Monthly Expenses') plt.axis('equal') plt.show()
Output