0

I am plotting a pie chart with pandas plot function, with the following code and matplotlib:

plt.figure(figsize=(16,8))
# plot chart
ax1 = plt.subplot(121, aspect='equal')
dfhelp.plot(kind='pie', y = 'Prozentuale Gesamt', ax=ax1, autopct='%1.1f%%',
            startangle=90, shadow=False, labels=dfhelp['Anzahl Geschäfte in der Gruppe'], legend = False, fontsize=14)
plt.show

the output looks like:

enter image description here

the problem is, the percentages and legend are overlapping, do you have any idea to fix that? For the plotting I used this question.

PV8
  • 5,799
  • 7
  • 43
  • 87
  • 1
    There's a [good sample](https://matplotlib.org/3.2.1/gallery/pie_and_polar_charts/pie_and_donut_labels.html) from the docs. – Henry Yik Jun 08 '20 at 07:19
  • It's happening because you have a lot of small wedges. You can probably follow [this approach](https://stackoverflow.com/a/23578860/6267086) to work around it. – frank Jun 08 '20 at 07:31

1 Answers1

2

This is an easier and more readable version of this answer in my opinion (but credits to that answer for making it possible).

import matplotlib.pyplot as plt
import pandas as pd

d = {'col1': ['Tesla', 'GM', 'Ford', 'Nissan', 'Other'], 
     'col2': [117, 95, 54, 10, 7]}
df = pd.DataFrame(data=d)
print(df)

# Calculate percentages points
percent = 100.*df.col2/df.col2.sum()

# Write label in the format "Manufacturer - Percentage %"
labels = ['{0} - {1:1.2f} %'.format(i,j) for i,j in zip(df.col1, percent)]

ax = df.col2.plot(kind='pie', labels=None) # the pie plot
ax.axis('equal') # Equal aspect ratio ensures that pie is drawn as a circle
ax.yaxis.label.set_visible(False) # disable y-axis label
# add the legend
ax.legend(labels, loc='best', bbox_to_anchor=(-0.1, 1.), fontsize=8)
plt.show()

enter image description here

thenewjames
  • 966
  • 2
  • 14
  • 25