Matplotlib is the most commonly used python package for data visualization. It is a 2D plotting library which take an array of numbers as an input and plot the data in form of different graphical representations such as bar graph, histogram, scatter plots, line plot etc. Suppose you’ve a graph consisting of multiple lines of different colors. To identify what these different colored lines represent, we use legends. In this tutorial, we will learn about how to add legend to a matplotlib in python to draw the graphs. If you want to learn more about Python Programming, visit Python Programming Tutorials.
Lets see in detail how can you create, display and perform different action with legends.
ADD A LEGEND to plot
Matplotlib has a legend() method which is used to describe what the different lines on the graph represent.
First of all, import the matplotlib library and define the values for x and y co-ordinates. Then, pass the co-ordinates of the graph you want to plot along with the label indicating what does that line represent to the plot() function. The plt.legend() command will add these labels as a legend on the graph. This is the mot simplest way of adding legends.
import matplotlib.pyplot as plt #initialize data x = [1, 2, 3, 4, 5] line1 = [1, 2, 3, 4, 5] line2 = [1, 4, 9, 16, 25] plt.plot(x, line1, label='x') plt.plot(x, line2, label='x^2') # Function add a legend plt.legend() # function to show the plot plt.show()
AdJUST POSITION OF legend in python
The legend can be placed at ‘upper left’, ‘upper right’, ‘lower left’, ‘lower right’ corner of the graph. The position of the legend can be adjusted by using keyword Loc in legend() command. Given the co-ordinates of two line plots, add a legend to the lower right corner of the graph.
import matplotlib.pyplot as plt y1 = [2, 3, 4,5.5,6,7] y2 = [1, 1.5, 3,5,7] # Function to plot plt.plot(y1) plt.plot(y2) plt.legend(["color blue", "color green"], loc ="lower right") # function to show the plot plt.show()
Similarly, you can also change the position of legend to upper right, upper left and lower left.
In this article, we have discussed how to add legend to a graph and how to adjust its position. If you want to learn more about matplotlib library and different graphical representations, contact us.