Title for matplotlib legend

Brandon Molyneaux picture Brandon Molyneaux · Jun 19, 2017 · Viewed 52.5k times · Source

I know it seems fairly redundant to have a title for a legend, but is it possible using matplotlib?

Here's a snippet of the code I have:

import matplotlib.patches as mpatches
import matplotlib.pyplot as plt

one = mpatches.Patch(facecolor='#f3f300', label='label1', linewidth = 0.5, edgecolor = 'black')
two = mpatches.Patch(facecolor='#ff9700', label = 'label2', linewidth = 0.5, edgecolor = 'black')
three = mpatches.Patch(facecolor='#ff0000', label = 'label3', linewidth = 0.5, edgecolor = 'black')

legend = plt.legend(handles=[one, two, three], loc = 4, fontsize = 'small', fancybox = True)

frame = legend.get_frame() #sets up for color, edge, and transparency
frame.set_facecolor('#b4aeae') #color of legend
frame.set_edgecolor('black') #edge color of legend
frame.set_alpha(1) #deals with transparency
plt.show()

I would want the title of the legend above label1. For reference, this is the output: Showing legend

Answer

Alper Fırat Kaya picture Alper Fırat Kaya · Jun 19, 2017

Add the title parameter to the this line:

legend = plt.legend(handles=[one, two, three], title="title",
                    loc=4, fontsize='small', fancybox=True)

See also the official docs for the legend constructor.