Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display actual values instead of percentages on my pie chart using matplotlibs [duplicate]

I want my piechart that I have created using matplotlib to show the actual value rather than just the percentge. Here is my code:

pie_shares= [i for i in mean.values()]
positions = [i for i in mean.keys()]
plt.pie(pie_shares,labels=positions, autopct='%1.1f%%', )
plt.show()
like image 713
jd55 Avatar asked Dec 14 '18 15:12

jd55


People also ask

How do I display actual values in Matplotlib pie chart?

Set the figure size and adjust the padding between and around the subplots. Make a pie chart using labels, fracs and explode with autopct=lambda p: <calculation for percentage>. To display the figure, use show() method.

How do you change a percentage into a pie chart?

Right click your Pie Chart. Choose "Chart Options". Under "Data Labels" Tab, choose "Show Value" instead of "Show Percent".

What is Autopct?

autopct enables you to display the percent value using Python string formatting. For example, if autopct='%. 2f' , then for each pie wedge, the format string is '%. 2f' and the numerical percent value for that wedge is pct , so the wedge label is set to the string '%. 2f'%pct .


1 Answers

If you want to display the actual value of the slices of your pie chart you must provide to the labels those values:

def autopct_format(values):
    def my_format(pct):
        total = sum(values)
        val = int(round(pct*total/100.0))
        return '{v:d}'.format(v=val)
    return my_format
plt.pie(pie_shares, labels = positions, autopct = autopct_format(pie_shares))

In the matplotlib resources, it is mentioned that autopct can be a string format and a function, so, we create a custom function that formats each pct to display the actual value from the percentages used commonly by this feature.

like image 138
SalvadorViramontes Avatar answered Oct 20 '22 21:10

SalvadorViramontes