Abhishek Kulkarni :
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.
krm :
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.
Guess you like
Origin http://43.154.161.224:23101/article/api/json?id=350722&siteId=1