Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matplotlib pie-chart: How to replace auto-labelled relative values by absolute values

I'm creating a pie-chart according to the matplotlib-demo: https://matplotlib.org/1.2.1/examples/pylab_examples/pie_demo.html

The percentage of each frac seems to be auto-labelled. How can I replace these auto-labelled relative values (%) plotted on the pie-chart by absolute values from fracs[]?

like image 976
zehpunktbarron Avatar asked Jan 05 '13 10:01

zehpunktbarron


People also ask

What is Autopct in pie chart?

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 '%.

How do I show numbers in a pie chart in MatPlotLib?

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 avoid overlapping of labels and Autopct in a MatPlotLib pie chart?

Use legend() method to avoid overlapping of labels and autopct. To display the figure, use show() method.

What is the correct function parameter and value input for creating a pie chart in MatPlotLib?

Matplotlib API has pie() function in its pyplot module which create a pie chart representing the data in an array. Parameters: data represents the array of data values to be plotted, the fractional area of each slice is represented by data/sum(data).


1 Answers

help(pie) says:

  *autopct*: [ *None* | format string | format function ]
    If not *None*, is a string or function used to label the
    wedges with their numeric value.  The label will be placed inside
    the wedge.  If it is a format string, the label will be ``fmt%pct``.
    If it is a function, it will be called.

so you can turn the percentages back into original values by multiplying by the total size of the pie and dividing by 100:

figure(1, figsize=(6,6))
ax = axes([0.1, 0.1, 0.8, 0.8])
labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'
fracs = [15, 30, 45, 10]
total = sum(fracs)
explode=(0, 0.05, 0, 0)
pie(fracs, explode=explode, labels=labels,
    autopct=lambda(p): '{:.0f}'.format(p * total / 100),
    shadow=True, startangle=90)
show()

like image 127
Gareth Rees Avatar answered Nov 15 '22 13:11

Gareth Rees