Save matplotlib legend as a separate image

Viewed 1939

I went through the following link before posting the question.

Get legend as a separate picture in Matplotlib

I am unable to replicate the provided solution for my example.

Here is my dataframe and the code. I want to save legend as a separate image.

df=pd.DataFrame(index=['A','B','C','D'], columns=['Values'])
df['Values'] = [0.45,0.28,0.21,0.3]

fig=plt.figure(figsize=(8,8))
ax1 = plt.subplot(121, aspect='equal')
df['Values'].dropna().plot(kind='pie', autopct='%1.0f%%', startangle=220, labels=None, 
                           colors=['#002c4b','#392e2c','#92847a','#ccc2bb','#6b879d'])

patches, labels = ax1.get_legend_handles_labels()
pp = ax1.legend(patches, labels=df.index, loc='center right', bbox_to_anchor=(0, 0.5), 
              fontsize=8, frameon=False, labelspacing=4)
ax1.axis('off')
plt.ylabel('')
img_name = 'unit1.png'   
plt.savefig(img_name,bbox_inches='tight', dpi = 300)
plt.close(fig)

Please suggest the way forward.

2 Answers

Somehow, the pandas interface to matplotlib seems to mess up the call to get_legend_handles_labels. The code below is the equivalent to what you have written, but uses matplotlib's interface instead.

import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame(index=['A','B','C','D'], columns=['Values'])
df['Values'] = [0.45, 0.28, 0.21, 0.3]

fig, ax = plt.subplots()
ax.pie(df["Values"].dropna(), 
       colors=['#002c4b', '#392e2c', '#92847a', '#ccc2bb', '#6b879d'], 
       autopct='%1.0f%%',
       startangle=220,
       labels=df.index,)
ax.legend(loc="best")

# get handles and labels for reuse
label_params = ax.get_legend_handles_labels() 

figl, axl = plt.subplots()
axl.axis(False)
axl.legend(*label_params, loc="center", bbox_to_anchor=(0.5, 0.5), prop={"size":50})
figl.savefig("LABEL_ONLY.png")

You might need to play around with the figaspect and prop to get optimal results for the label size and positioning.

You are not creating a separate figure instance to use for drawing the legend as the accepted answer in the linked question does. What you want is something like this

df=pd.DataFrame(index=['A','B','C','D'],columns=['Values'])
df['Values']=[0.45,0.28,0.21,0.3]

fig = plt.figure(figsize=(8,8))
figlegend = plt.figure(figsize=(3,2))

# fig.subplot adds subplot to fig instead of to the 'current figure' like plt.subplot
ax1 = fig.subplot(121, aspect='equal')
df['Values'].dropna().plot(kind='pie', autopct='%1.0f%%', startangle=220, labels=None, 
                           colors=['#002c4b','#392e2c','#92847a','#ccc2bb','#6b879d'])

patches, labels = ax1.get_legend_handles_labels()
# Get rid of the legend on the first plot, so it is only drawn on the separate figure
ax1.get_legend().remove()  
figlegend.legend(patches, labels=df.index)

fig.savefig('image.png')
figlegend.savefig('legend.png')
plt.close(fig)
plt.close(figlegend)

This will create two separate figure instances, one for the plotting and the second for the legend, allowing them to be saved as separate files.

Related