In this article, we will learn how to add text inside a plot using Matplotlib. But not just that. We will also look at how we can position this text inside the plot.
In our earlier articles, we had already seen how we can add titles and axis labels to our plot. Right? So this article will be a follow up of that. But only that we will be adding text inside the plot itself. This is unlike others where we added labels and titles outside the plot.
So how do we go about doing this? How can we add text inside a plot? If we can, can it be positioned wherever we want within the plot? These are some of the questions we will be answering next!
So let us start with the first question:
How To Add Text Inside A Matplotlib Plot Using Python
So to answer this, let us draw a simple plot using the following code:
import matplotlib.pyplot as plt import numpy as np x = np.arange(0, 20, 1) y = np.arange(0, 2, 0.1) plt.plot(x, y) plt.show()
So this will give us a simple plot with a linear line that looks like this:
Okay. This is great! But now how do we go about adding a piece of text inside this plot? Let me say I want a piece of text that reads “This is cool!” written above the blue line, but somewhere in the middle? Can I do that in Matplotlib?
The text( ) function
Of course you can! Matplotlib provides you with a very specific function for you to do just that! The function is called the text( ) function and it is part of the plt module of Matplotlib.
So what does the signature of this text( ) function look like? Here it is:
plt.text(x, y, text)
In the above text( ) function signature,w e see that it takes in 3 parameters – x, y, & text. But what do they do? Well, the parameters x & y gives the co-ordinates where the text is to be written. While the “text” parameter specifies the text we want to write!
So how does this all workout for us where we want to say “This is cool!” above the blue line? Well, first we need to set the x & y co-ordinates.
From the plot above, we can choose a value that is above the line and somewhere in the middle. Right? So what would be that value? Well how about it being 5 along the x-axis and 1 along the y-axis? In which case, we can call the text( ) function as follows:
plt.text(5, 1, 'This is cool!')
We will call this function just before plotting. So our final code will then become:
import matplotlib.pyplot as plt import numpy as np x = np.arange(0, 20, 1) y = np.arange(0, 2, 0.1) plt.text(5, 1, 'This is cool!') plt.plot(x, y) plt.show()
So how will the plot look like for this code? Take a look at it for yourself!
Now that is what we wanted right?!
So there you have it. This is how we can add text inside a plot in Matplotlib using Python. Hope it was pretty easy to follow. But if you have any questions, do let me know in the comments below. I will be more than happy to help!
So until next time, have a nice day! 🙂