I have done a clustering algorithm and represented the results in a pie chart as shown below.
fig, ax = plt.subplots(figsize=(20, 10), subplot_kw=dict(aspect="equal"))
contents = []
for k,v in clusters.items():
indi= str(len(clusters[k])) + " users " + "Cluster_"+ str(k)
contents.append(indi)
#contents = ['23 users Cluster_0', '21 users Cluster_1']
data = [float(x.split()[0]) for x in contents]
Cluster= [x.split()[-1] for x in contents]
def func(pct, allvals):
absolute = int(pct/100.*np.sum(allvals))
return "{:.0f}%\n({:d} users)".format(pct, absolute)
wedges, texts, autotexts = ax.pie(data, autopct=lambda pct: func(pct, data),
textprops=dict(color="w"))
ax.legend(wedges, Cluster,
title="CLuster",
loc="center left",
bbox_to_anchor=(1, 0, 0.5, 1))
plt.setp(autotexts, size=10, weight="bold")
ax.set_title("Distribution of users: A pie chart")
Even though the users are 23 and 21 in each cluster, the piechart shows 22 and 20. This is due to the conversion to int and some float values are cut off in the function def func().
But, to fix this I wrote the below code and it works:
def func(percentage, allvals):
absolute = int(np.sum(allvals))
newV = (percentage/100)*absolute
roundnewV = round(newV)
intnewV = int(roundnewV)
return "{:.0f}%\n({:d} users)".format(percentage, intnewV)
Is this a good way to save the original form of integer and not lose out any value?