PV8
PV8

Reputation: 6270

Overlapping legend for pandas plot with a pie chart

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.

Upvotes: 0

Views: 2357

Answers (1)

thenewjames
thenewjames

Reputation: 1164

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

Upvotes: 3

Related Questions