![]() |
VOOZH | about |
Matplotlib is a plotting library in Python to visualize data, inspired by MATLAB, meaning that the terms used (Axis, Figure, Plots) will be similar to those used in MATLAB. Pyplot is a module within the Matplotlib library which is a shell-like interface to Matplotlib module.
It provides almost any kind of plot that we can think of. In this post, we will focus on a more specific topic which is adding text on matplotlib plot. The following commands are used to create text in the matplotlib plot.
| Commands | Description |
| text | This is used for adding text at an arbitrary location of the Axes. |
| annotate | This is used for adding an annotation, with an optional arrow, at an arbitrary location of the Axes. |
| set_xlabel | This is used for adding label to the Axes' x-axis. |
| set_ylabel | This is used for adding label to the Axes' y-axis. |
| set_title | This is used for adding title to the Axes. |
| text | This is used for adding text at an arbitrary location of the Figure. |
| suptitle | This is used for adding title to the Figure. |
We will see each of the commands one by one, first, let's create a basic plot of Day v/s Question on which we will add various text objects.
Code:
Output:
👁 ImageThe output plot looks very simple. Now, let's see some text commands to add it on our plot.
It is better to adjust the range on y-axis so that we can have some space to add text later on. For this, we will use ax.axis() which allows specifying value ranges (the first two for x-axis and the other two for y-axis).
Now, let's add its title and names of x-axis and y-axis.
Code:
Output:
👁 ImageNow, it looks better than the previous version. It's the time to add text to our plot. First, let's see about them.
axes.text() is used to add text at an arbitrary location of the Axes. For this we need to specify the location of the text and of course what the text is. For instance, the following code will add “Practice on GFG” text. It will located according to the point whose coordinates are specified ([1,13] in this case). The parameter bbox is used to capture the text with a box. As argument to bbox parameter, we pass a dictionary which includes formatting styles.
Code:
If we want to do not have to box the text then simply do not assign anything to the bbox parameter. The following code adds the specified text without a box.
Code:
We can also add text with annotations.
axes.annotate() is used to add an annotation, with an optional arrow, at an arbitrary location of the Axes. Its xy parameter contains the coordinates for arrow and xytext parameter specifies the location of the text. Arrowprops parameter is used to style the arrow.
For instance, we can mark the peak value of the Day-Question data with an annotation.
Code:
Let’s put all this together and see the final code.
Code: