Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matplotlib, Pandas, Pie Chart Label mistakes

I have generated a pie chart using both Pandas wrapper counts.plot(kind='pie') and Matplotlib straight `plt.pie(counts).

The issue is the labelling. Using both the pie chart represents correctly in terms of values = pie wedge, however the labels are off when I start introducing custom colors and legends.

enter image description here

The pie chart labels are correct, but the legend labels are drawing in relation to their label order in group_name, not their values. Any ideas on how to fix this?

Code =

group_names = ['2-3 km', '3-5 km','5-7 km','7-10 km','10-20 km','20-50 km','50-75 km','75-100 km','>100 km']

df['bins'] = pd.cut(df['distkm'], bins)
df['categories'] = pd.cut(df['distkm'], bins, labels=group_names)

counts = df['categories'].value_counts()
plt.axis('equal')
explode = (0, 0, 0,0.1,0.1,0.2,0.3,0.4,0.6)
colors = ['#191970','#001CF0','#0038E2','#0055D4','#0071C6','#008DB8','#00AAAA','#00C69C','#00E28E','#00FF80',]
counts.plot(kind='pie', fontsize=17,colors=colors,explode=explode)
plt.legend(labels=group_names,loc="best")

plt.show()

Data look like

20-50 km     1109
50-75 km      696
10-20 km      353
75-100 km     192
3-5 km        168
7-10 km        86
5-7 km         74
>100 km        65
2-3 km         53
dtype: int64
like image 620
hselbie Avatar asked Feb 18 '16 17:02

hselbie


People also ask

How do you avoid overlapping of labels and Autopct in a matplotlib pie chart?

To avoid overlapping of labels and autopct in a matplotlib pie chart, we can follow label as a legend, using legend() method.

How do you remove the Y label from a pie chart?

To hide the label on the left side in matplotlib, we can use plt. ylabel("") with ablank string.

How do you add text to a pie chart in Python?

text() is the main function we can use to add text to a plot. We start by adding the string “function” with fontsize=12 to the location (10, 20). By default, the location is given in data coordinates. The coordinate system can be changed using the transform parameter.


1 Answers

Creating the value counts, if I take off the auto sort, the legend draws correctly.

counts = df['categories'].value_counts(sort=False)enter image description here

like image 51
hselbie Avatar answered Nov 03 '22 15:11

hselbie