Nelly Yuki
Nelly Yuki

Reputation: 419

python matplotlib pie chart unexpected values

I am learning using matplotlib visualizations and was doing a simple pie chart. I am wondering why when I plot this, the percentages are as follow:

image plot

I was expecting it to show 40% frogs and 50% hogs...

Do I need to normalize or something?

labels = 'Frogs', 'Hogs'

sizes = [40,50]
#explode = (0, 0.1, 0, 0)  # only "explode" the 2nd slice (i.e. 'Hogs')

fig1, ax1 = plt.subplots()
ax1.pie(sizes,labels=labels, autopct='%1.1f%%')
ax1.axis('equal')  # Equal aspect ratio ensures that pie is drawn as a circle.

plt.show()

Upvotes: 0

Views: 1732

Answers (2)

JohanC
JohanC

Reputation: 80279

pie has a parameter normalize:

normalize: None or bool, default: None

When True, always make a full pie by normalizing x so that sum(x) == 1. False makes a partial pie if sum(x) <= 1 and raises a ValueError for sum(x) > 1.

When None, defaults to True if sum(x) >= 1 and False if sum(x) < 1.

In the future, the default will always be True, so False needs to be set explicitly.

To have some percentages, the values can be divided by 100, and a partial pie will be drawn:

import matplotlib.pyplot as plt

fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(6, 2))

labels = ['Frogs', 'Hogs']
sizes = [40, 50]
ax1.pie([s / 100 for s in sizes], normalize=False, labels=labels, autopct='%1.1f%%')
ax1.axis('equal')
ax1.set_title('40% frogs, 50% hogs')

ax2.pie([0.15], normalize=False, labels=['Frogs'], autopct='%1.0f%%')
ax2.axis('equal')
ax2.set_title('15% frogs')

plt.tight_layout()
plt.show()

partial pies

Upvotes: 1

smp55
smp55

Reputation: 403

As BigBen indicated in his comment, pie charts use 100% total. Your values of 50 and 40 do not add up to 100, so it takes them as total counts, not percent, and therefore assumes the grand total of frogs and hogs to be 90, not 100.

Upvotes: 1

Related Questions