I tri to display on a pie chart :
- labels
- Value
- Percentage
I know how to do to display both the value and the percentage :
def autopct_format(values):
def my_format(pct):
total = sum(values)
val = int(round(pct*total/100.0)/1000000)
LaString = str('{:.1f}%\n{v:,d}'.format(pct, v=val))
return LaString
return my_format
But I don't know how to display the labels, I tried to do the following :
def autopct_format(values,MyString):
def my_format(pct,MyString):
total = sum(values)
val = int(round(pct*total/100.0)/1000000)
LaString = str('{0},{:.1f}%\n{v:,d}'.format(MyString, pct, v=val))
return LaString
return my_format
But this does throw the following error :
TypeError: my_format() missing 1 required positional argument: 'MyString'
Below is the reproducible example :
import matplotlib.pyplot as plt
import numpy as np
def autopct_format(values,MyString):
def my_format(pct,MyString):
total = sum(values)
val = int(round(pct*total/100.0)/1000000)
LaString = str('{0},{:.1f}%\n{v:,d}'.format(MyString, pct, v=val))
return LaString
return my_format
fig, ax = plt.subplots(1,1,figsize=(10,10),dpi=100,layout="constrained")
ax.axis('equal')
width = 0.3
#Color
A, B, C=[plt.cm.Blues, plt.cm.Reds, plt.cm.Greens]
#OUTSIDE
cin = [A(0.5),A(0.4),A(0.3),B(0.5),B(0.4),C(0.3),C(0.2),C(0.1), C(0.5),C(0.4),C(0.3)]
Labels_Smalls = ['groupA', 'groupB', 'groupC']
labels = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'I']
Sizes_Detail = [4,3,5,6,5,10,5,5,4,6]
Sizes = [12,11,30]
pie2, _ ,junk = ax.pie(Sizes_Detail ,radius=1,
#labels=labels,labeldistance=0.85,
autopct=autopct_format(Sizes_Detail,labels) ,pctdistance = 0.7,
colors=cin)
plt.setp(pie2, width=width, edgecolor='white')
#INSIDE
pie, _ = ax.pie(Sizes, radius=1-width,
#autopct=autopct_format(Sizes) ,pctdistance = 0.8,
colors = [A(0.6), B(0.6), C(0.6)])
plt.setp(pie, width=width, edgecolor='white')
plt.margins(0,0)
and there is the excepted output :
CodePudding user response:
You can send the labels with the values to autopct_format
and keep track on the calls to inner my_format
def autopct_format(values, labels):
def my_format(pct):
total = sum(values)
val = int(round(pct * total / 100.0) / 1000000)
LaString = '{l}\n{p:.1f}%\n{v:,d}'.format(l=labels[autopct_format.counter], p=pct, v=val)
print(LaString)
autopct_format.counter = 1
return LaString
autopct_format.counter = 0
return my_format
....
labels = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J']
Sizes_Detail = [4, 3, 5, 6, 5, 10, 5, 5, 4, 6]
pie2, _, junk = ax.pie(Sizes_Detail, radius=1,
autopct=autopct_format(Sizes_Detail, labels),
pctdistance=0.7, colors=cin)