Search code examples
pythonpandasmatplotlibjupyter-notebookpie-chart

Common legend for multiple pie chart plots


How do i set a commond legend for both chart at the bottom of the chart. I tried using fig.legend but do not know how to write it correctly. Thanks!!

import pandas as pd

# Intialise data to Dicts of series.
d = {'Oil' : pd.Series([1.0, 17.0, 0.3, 81.7],
                       index =['Others', 'Commercial', 'Industrial', 'Domestic']),
        'Coal' : pd.Series([3, 34.8,  38.6, 23.6],
                        index =['Others', 'Commercial', 'Industrial', 'Domestic'])}
  
# creates Dataframe.
df = pd.DataFrame(d)

fig, axes = plt.subplots(1,2, figsize=(15,4.5))

fig.suptitle('Customers Profile and Energy Sold per Sector', fontweight='bold', fontsize=20)
for ax, col in zip(axes, df.columns):
    ax.pie(df[col], wedgeprops=dict(linewidth = 3, edgecolor = 'white'), colors=['#EE8434','#C95D63', '#AE8799','#717EC3'],startangle=90, autopct='%.2f%%', pctdistance=1.2)
     
#fig.legend(ax, df.index, 'upper left')


Solution

  • The answer was found in link suggested by @henryecker

    for ax, col in zip(axes, df.columns):
        chart = ax.pie(df[col])
         
    fig.legend(chart[0], df.index, 'lower center')