Custom Legends with Matplotlib - GeeksforGeeks

28 Nov, 2021
In this article, you learn to customize the legend in matplotlib. matplotlib is a popular data visualization library. It is a plotting library in python and has its numerical extension NumPy.
Legend is an area of the graph describing each part of the graph. A graph can be simple as it is. But adding the title, X label, Y label and legend will be more clear. By seeing the names we can easily guess what the graph is representing and what type of data it is representing.  
Let us first see how to create a legend in matplotlib.  
syntax: legend(*args, **kwargs)
This can be called as follows,
legend() -> automatically detects which element to show. It does this by displaying all plots that have been labeled with the label keyword argument.  
legend(labels) -> Name of X and name of Y that is displayed on the legend 
legend(handles, labels) -> A list of lines that should be added to the legend. Using handles and labels together can give full control of what should be displayed in the legend. The length of the legend and handles should be the same.
Python3
# importing libraryimport matplotlib.pyplot as plt  # plotting valuesa = [1, 2, 3, 4]b = [1, 4, 9, 16]  # PLotting using matplotlibplt.plot(a, label="A")plt.plot(b, label="B")  # Creating legendplt.legend()
Output:
legend
Legend adds meaning to the graph plots. Adding the font, location, and many more, make the legend more legible and easily recognizable. Now, let’s see some sample programs to customize the legends of the plots.
Sometimes the legend may or may not be in the appropriate place. In matplotlib, we can also add the location where we want to place it. With this flexibility, we can place the legend somewhere where it does not overlay the plots, and hence the plots will look much cleaner and tidier. 
Syntax: legend(loc=”)
It can be passed as follows, 
‘upper left’, ‘upper right’, ‘lower left’, ‘lower right’ -> It is placed on the corresponding corner of the plot.
‘upper center’, ‘lower center’, ‘center left’, ‘center right’ -> It is placed on the center of  corresponding edge. 
‘center’ -> It is placed exact center of the plot.
‘best’ -> It is placed without the overlapping of the  artists
For example, 
Python3
# importing libraryimport matplotlib.pyplot as plt  # plotting valuesa = [1, 2, 3, 4]b = [1, 4, 9, 16]  # PLotting using matplotlibplt.plot(a, label="A")plt.plot(b, label="B")  # Creating legend# Adding the locationplt.legend(loc='center left')
Output:
center left
To make the legend more appealing we can also change the font size of the legend, by passing the parameter font size to the function we can change the fontsize inside the legend box just like the plot titles. 
Syntax: legend(fontsize=”)
It can be passed as, ‘xx-small’, ‘x-small’, ‘small’, ‘medium’, ‘large’, ‘x-large’, ‘xx-large’
Example:
Python3
# importing libraryimport matplotlib.pyplot as plt  # plotting valuesa = [1, 2, 3, 4]b = [1, 4, 9, 16]  # PLotting using matplotlibplt.plot(a, label="label1")plt.plot(b, label="label2")  # Creating legendplt.legend(fontsize='xx-large')
Output:
Changing font size
Sometimes we can feel that it would be great if the legend box was filled with some color to make it more attractive and makes the legends stand out from the plots. Matplotlib also covers this by letting us change the theme of the legend by changing the background, text, and even the edge color of the legend.-+
Syntax: 
legend(labelcolor=”)
labelcolor is used to  change the color of the text.
legend(facecolor=”)
facecolor is used to change background color of the legend.
legend(edgecolor=”)
edgecolor is used to change the edge color of the legend
Example:
Python3
# importing libraryimport matplotlib.pyplot as plt  # plotting valuesa = [1, 2, 3, 4]b = [1, 4, 9, 16]  # PLotting using matplotlibplt.plot(a, label="label1")plt.plot(b, label="label2")  # Creating legend# Adding color to the legendplt.legend(labelcolor='white', facecolor='black',           edgecolor='red', fontsize='xx-large')
Output:
changing color of the legend.
In the above example, you can clearly see which keyword arguments give color to the legend.
If you see the legend box,
Syntax: 
legend(markerfirst = bool, default: True)
By default, the marker is placed first and the label is placed second. marker first parameter is used to change the position of the marker. By making it False, the marker and labels places will be swapped.
Example:
Python3
# importing libraryimport matplotlib.pyplot as plt  # plotting valuesa = [1, 2, 3, 4]b = [1, 4, 9, 16]  # PLotting using matplotlibplt.plot(a, label="label1")plt.plot(b, label="label2")  # Creating legendplt.legend(markerfirst=False)
 Output:
markerfirst = False
We can make the legend have some of the basic CSS properties like adding a shadow, adding a frame and making the corners round, and also let us add transparency to the legend box if you don’t want to cover those small details in the plot by a frame.
shadow -> This argument gives shadow behind the legend. 
frameon  -> Gives the frame to legend.
fancybox -> Gives round edges to the legend. 
framealpha -> Gives transparency to legend background.
Python3
# importing libraryimport matplotlib.pyplot as plt  # plotting valuesa = [1, 2, 3, 4]b = [1, 4, 9, 16]  # PLotting using matplotlibplt.plot(a, label="label1")plt.plot(b, label="label2")  # Creating legend# Adding shadow and fancybox to the legendplt.legend(shadow=True, fancybox=True)
Output:
Shadow and fancybox
Python3
#importing libraryimport matplotlib.pyplot as plt  #plotting valuesa = [1,2,3,4]b = [1,4,9,16]  #PLotting using matplotlibplt.plot(a, label="label1")plt.plot(b, label="label2")  #Creating legend#removing frameplt.legend(frameon = False)
Output:
Removes the frame
Adding a title to the legend will be an important aspect to add to the legend box. The title parameter will let us give a title for the legend and the title_size let us assign a specific fontsize for the title.
Syntax:
legend(title=”” , title_fontsize=”)
title gives title to the legend
title_fontize gives size to the title.
It can be, ‘xx-small’, ‘x-small’, ‘small’, ‘medium’, ‘large’, ‘x-large’, ‘xx-large’
Example: 
Python3
# importing libraryimport matplotlib.pyplot as plt  # plotting valuesa = [1, 2, 3, 4]b = [1, 4, 9, 16]  # PLotting using matplotlibplt.plot(a, label="label1")plt.plot(b, label="label2")  # Creating legend# giving title and fontsizeplt.legend(title="Legend", title_fontsize='xx-large')
output:
Title to the legend
Picked
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()