Matplotlib Tutorial 2
We have already learned about plot() and show() function and we are aware of the following code given below.
import matplotlib.pyplot as pl x = [1,2,3] y = [4,5,7] pl.plot(x,y) pl.show()
Now we will learn how to label the x-axis and y-axis and place the title.
XLABEL YLABEL TITLE
We have xlabel() ylabel() and title() function to perform the job.
import matplotlib.pyplot as pl
x = [1,2,3]
y = [4,5,7]
pl.plot(x,y)
pl.xlabel("X coordinates")
pl.ylabel('Y coordinates')
pl.title("Matplotlib Tutorial 2")
pl.show()
In the above code, we have used
- xlabel(“X coordinates”) function to label the x-axis
- ylabel(“Y coordinates”) function to label the y-axis
- title(“Matplotlib Tutorial 2”) to give a title for our line graph
Please play with the below code in order to label the horizontal and vertical axis along with title information.
What are Legends in Matplotlib & When to use them:
Suppose, if we have more than one line in our graph, it is hard to imagine which are the different lines, if we do not associate them with any identifier or label. In order to properly identify our lines with different color codes and labels, we use legends. A legend in Matplotlib depicts the information in a rectangular box such that different labels assigned to each line along with color. Legend information can be shown both inside the graph or outside the graph.
Let assume, we have three lines, with three lists of coordinates.
x = [1,2,3] y = [4,5,7] x1 = [1,2,3] y1 = [1,5,7] x2 = [1,2,3] y2 = [1,0,8]
We need to use plot function, to label all the three lines and need to use legend function before show() function.
import matplotlib.pyplot as pl
x = [1,2,3]
y = [4,5,7]
x1 = [1,2,3]
y1 = [1,5,7]
x2 = [1,2,3]
y2 = [1,0,8]
pl.plot(x,y, label="First line")
pl.plot(x1,y1, label="second line")
pl.plot(x2,y2, label="third line")
pl.xlabel("X coordinates")
pl.ylabel('Y coordinates')
pl.title("Matplotlib Tutorial 2")
pl.legend()
pl.show()
Please see the below code in order to label the different lines represented by legend. Feel free to edit the code using Python online code editor.
Note: In this graph, the legend is inside the graph. There are different location values for the legend that can be set using pl.legend(“best”)
value can be: best, upper right, upper left, lower left, lower right, right, center left, center right, lower center, upper center, center
The default value is best