Annotation of plot using matplotlib in Python
In this tutorial, we will learn the annotation of a plot using matplotlib in Python. We will see how to add labels and titles using matplotlib.
Annotation:– The word annotation means a note by way of explanation or comments added to a text or diagram.
In this article, we will learn how to annotate a plot using matplotlib in python. Annotation is a very good way of plotting a diagram or graph as annotation contains all the basic and important information about that diagram or graph and it also helps the users to understand that how to read that graph or diagram. If we don’t annotate a graph or diagram then it doesn’t contain any information about that graph or diagram and it is not understandable for the user. So, we always try to annotate the graph.
Annotating plot by taking some example using matplotlib
From my point of view, there are many types of annotation but we discuss two important annotations we can include in our data visualization:-
- Adding labels
- Titles adding
Adding labels in the plot:- As this the easiest method, as in many software tools it defaults to create a data legend and place it anywhere inside the plot but disconnected from the diagram or graph. Let’s understand it by taking an example.
import matplotlib.pyplot as plt import numpy as np X = np.array([1,2,3,4,5]) Y = X**2 plt.plot(X, '-', label='linear') plt.plot(Y, '-', label='squared') plt.xlabel('X') plt.ylabel('Y') plt.legend(loc='best') plt.show()
In the above example, we first imported two important modules to plot a graph i.e. numpy and matplotlib.pyplot, then we created a numpy array and stored it in a variable named as X and then we established a relation between X and Y i.e., Y=X2. Then we used the legend object and passed one argument inside it which finds the best location of labels inside the plot.
Adding titles in plot :- It also plays an important role in the annotation of plot as it states the topic of the plot that the graph or diagram is related to what types of topics. Let’s understand this through an example:
import matplotlib.pyplot as plt import numpy as np X = np.array([1,2,3,4,5]) Y = X**2 plt.plot(X) plt.plot(Y) plt.xlabel('X') plt.ylabel('Y') plt.title("Graph of a line(y = mx+c) and a parabola(y = x^2)") plt.show()
In this example, the only difference in this example is that we used an object plt.title() and passed the required information about the graph, which will get printed as title of the plot.
For study annotation in deep please refer to the documentation of matplotlib.pyplot
You can also read these articles: