Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Adding a black edgecolor around to legend entries in matplotlib

I’ve made this pie chart in python and I would like to know how to add a black frame around each boxcolor in the legend. I mean around of each color square like in qgis for example.

array = np.array([17.96, 10.74, 12.97,  3.47,  8.52,  3.28,  8.56, 16.79, 17.69,
        0.02])
colors = ['#32560a','#8ba023','#748030','#bcb877', '#ccbb86','#807d51','#d3ee99', '#e5e4e2', '#006fff', '#ffffff']
labels = ['Decidious forest', 'Mesic upland shrub', 'Xeric upland shrub', 'Tundra (non-tussock)','Tundra (tussock)','Prostrate shrub tundra', 'Wetland', 'Bare', 'Water', 'Snow']
fig, ax = plt.subplots(figsize=(10, 8))
ax.pie(array,labels=None,colors=colors, autopct='%0.2f%%', startangle=180, pctdistance=0.85, labeldistance = 1.05,textprops={'fontsize':10})
leg = plt.legend(labels,loc='lower center',bbox_to_anchor=(0.5,-0.05), ncol=5,title='SnowModel Land classes')
leg.get_frame().set_linewidth(0.0)
plt.tight_layout()
handles, labels = ax.get_legend_handles_labels()

enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

A way to do it is by specifying the handles param with the help of Patch:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Patch

array = np.array([17.96, 10.74, 12.97,  3.47,  8.52,  3.28,  8.56, 16.79, 17.69,0.02])
colors = ['#32560a','#8ba023','#748030','#bcb877', '#ccbb86','#807d51','#d3ee99', '#e5e4e2', '#006fff', '#ffffff']
labels = ['Decidious forest', 'Mesic upland shrub', 'Xeric upland shrub', 'Tundra (non-tussock)','Tundra (tussock)','Prostrate shrub tundra', 'Wetland', 'Bare', 'Water', 'Snow']
outline_handles = [Patch(facecolor=color, edgecolor='black', label=label) for color, label in zip(colors, labels)]

fig, ax = plt.subplots(figsize=(10, 8))
ax.pie(array,labels=None,colors=colors, autopct='%0.2f%%', startangle=180, pctdistance=0.85, labeldistance = 1.05,textprops={'fontsize':10})
leg = plt.legend(handles=outline_handles, loc='lower center',bbox_to_anchor=(0.5,-0.05), ncol=5,title='SnowModel Land classes')
leg.get_frame().set_linewidth(0.0)
plt.tight_layout()
handles, labels = ax.get_legend_handles_labels()

Pie chart with outlined handles

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading