Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Showing Percentages on Donut Chart using Matplotlib

I have the following code to generate a pretty donut chart:

%matplotlib inline
import matplotlib.pyplot as plt

size_of_groups=[12,11,30,3]

colors = ['#F92969','#FACA0C','#17C37B','#D9DFEB']

my_pie,_ = plt.pie(size_of_groups,radius = 1.2,colors=colors)

plt.setp(my_pie, width=0.6, edgecolor='white') # 

plt.show()

I'm not doing the method where you put a circle in the middle of your donut chart - this is because I need the interior of my plot to be transparent for another purpose.

Right now, the above outputs this: graph

However, when I change the code to add the ,autopct="%.1f%%" line, it breaks, but outputs a pie chart with labels anyway (though not a donut):

%matplotlib inline
import matplotlib.pyplot as plt

size_of_groups=[12,11,30,3]

colors = ['#F92969','#FACA0C','#17C37B','#D9DFEB']

my_pie,_ = plt.pie(size_of_groups,radius = 1.2,colors=colors,autopct="%.1f%%")

plt.setp(my_pie, width=0.6, edgecolor='white') # 

plt.show()

graph2

The error is:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-39-ada97a3edee3> in <module>
     13 
     14 # Create a pieplot
---> 15 my_pie,_ = plt.pie(size_of_groups,radius = 1.2,colors=colors,autopct="%.1f%%")
     16 
     17 #,autopct="%.1f%%"

ValueError: too many values to unpack (expected 2)

I'm unclear as to what this is, and I'm especially bamboozled that I'm having some output anyway, just without the hole in the center. Any help would be appreciated!

like image 921
Yeahprettymuch Avatar asked Jan 21 '26 03:01

Yeahprettymuch


1 Answers

Try this:

my_pie,_,_ = plt.pie(size_of_groups,radius = 1.2,colors=colors,autopct="%.1f%%")

Adding autopct adds another return value to plt.pie, so we need to assign it to something - hence the extra ,_.

autotexts : list

A list of Text instances for the numeric labels. This will only be returned if the parameter autopct is not None.

Output:

enter image description here

like image 187
CDJB Avatar answered Jan 22 '26 15:01

CDJB



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!