In this article, we are going to add a legend to the depicted images using matplotlib module. We will use the matplotlib.pyplot.legend() method to describe and label the elements of the graph and distinguishing different plots from the same graph.
Syntax: matplotlib.pyplot.legend( [“title_1”, “Title_2”], ncol = 1 , loc = “upper left” ,bbox_to_anchor =(1, 1) )
- ncol: [takes int, optional parameter] the default value is 1. It represents the number of columns in legend.
- loc: [takes string, optional parameter] the default value is “best” i.e “upper left”. It represents the location of the legend. Other options can be: “best”, “upper right”, “upper left”, “lower left”, “lower right” , “right”, “center left”, “center right”, “lower center”, “upper center”, “center”.
- bbox_to_anchor: [takes a list or tuple of 2 int/float, optional parameter ]. It represents the co-ordinates of legend on the graph. Both x and y co-ordinates are mandatory to give.
Note : We may label the elements of the plot in matplotlib.pyplot.scatter() using “label” parameter. However, to show it matplotlib.pyplot.legend() must be written.
Note: If matplotlib.pyplot.legend() is not written in code, then labels will not be shown.
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course