Title for matplotlib legend

PythonMatplotlibPatch

Python Problem Overview


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

Python Solutions


Solution 1 - Python

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.

Solution 2 - Python

Just to add to the accepted answer that this also works with an Axes object.

fig, ax = plt.subplots()
ax.plot([0, 1, 2], [0, 1, 4], label='some_label') # Or however the Axes was created.
ax.legend(title='This is My Legend Title')

Solution 3 - Python

In case you have an already created legend, you can modify its title with set_title(). For the first answer:

legend = plt.legend(handles=[one, two, three], loc=4, fontsize='small', fancybox=True)
legend.set_title("title")   
# plt.gca().get_legend().set_title() if you didn't store the
# legend in an object or you're loading a saved figure. 

For the second answer based on Axes:

fig, ax = plt.subplots()
ax.plot([0, 1, 2], [0, 1, 4], label='some_label') # Or however the Axes was created.
ax.legend()
ax.get_legend().set_title("title")

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBrandon MolyneauxView Question on Stackoverflow
Solution 1 - PythonAlper Fırat KayaView Answer on Stackoverflow
Solution 2 - PythonErnestScribblerView Answer on Stackoverflow
Solution 3 - PythonibarrondView Answer on Stackoverflow