1

I would like to know I can I add callouts in a pie chart. I have this dataset:

       ID   Colour
0   27995   red
1   36185   orange
2   57204   blue
3   46009   red
4   36241   white
5   63286   blue
6   68905   blue
7   3798    green
8   53861   yellow
...
199 193 brown

and when I try to generate a pie chart using pandas:

df.groupby(Colour).size().plot(kind='pie',figsize=(15,15), label="", labeldistance=0.8, autopct='%1.0f%%',  pctdistance=0.5,legend=True)

I get an awful chart where colours overlap since slices are very tiny and percentage values overlap too. I know that it could be easier to manage the chart as follows:

How to avoid overlapping of labels & autopct in a matplotlib pie chart?

but I have not been able to use the code in the answer in my case.

Can you please tell me what I should change in the code suggested in that answer?

still_learning
  • 776
  • 9
  • 32

1 Answers1

4

Fine-tuning is easier to deal with in 'matplotlib'. I used the official reference as an example to modify your data. From here. The point is explode=(), which sets the number of slices to be cut out of a tuple.

import matplotlib.pyplot as plt

colours = ['red', 'orange', 'blue', 'white', 'green', 'yellow', 'brown']

labels = colours
sizes = df.groupby('Colour').size().tolist()
# only "explode" the 3nd,4th slice (i.e. 'Blue, White')
explode = (0, 0, 0.2, 0.2, 0, 0, 0)

fig1, ax1 = plt.subplots()
ax1.pie(sizes, explode=explode, labels=labels, autopct='%1.1f%%', shadow=True, startangle=90, colors=colours)

# Equal aspect ratio ensures that pie is drawn as a circle.
ax1.axis('equal')  

plt.show()

enter image description here

r-beginners
  • 31,170
  • 3
  • 14
  • 32
  • Thanks @r-beginners. I am receiving this error: ValueError: 'explode' must be of length 'x'. Do you know how I could fix it? – still_learning Aug 26 '20 at 23:26
  • 1
    The error may be that the number of elements in the pie chart is not the same as the number of elements of the `explode=()`. – r-beginners Aug 27 '20 at 01:51