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:
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.
To set a legend with title, we use legend() method with labels and title arguments. Then we get the legend title, by using the get_title() function. To change the font size of legend's title, we use set_fontsize() method and set it to x-large. To add a title to the plot, we use title() method.
Normally plot the data. Display plot. In this example, we will draw different lines with the help of matplotlib and Use the title argument to plt.legend () to specify the legend title. In this example, we will draw a Bar Graph with the help of matplotlib and Use the title argument to plt.legend () to specify the legend title.
Similarly, title in Matplotlib is a text area at the top of the Graph which shows the context of the graph. Labels is the information that is displayed on the legend, without the labels legends would be empty. Let’s create a graph of multiple data sets and see how to differentiate between them:
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.
Labeling existing plot elements To make a legend for lines which already exist on the Axes (via plot for instance), simply call this function with an iterable of strings, one for each legend item. For example:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With