Add text to plot matplotlib in Python

In this Python tutorial, we will learn how to add text to a plot using matplolib in python. And we will also cover the following topics:

  • Add text to plot matplotlib
  • Add text to plot matplotlib example
  • Add mutiple line text to plot matplotlib
  • Add text to plot matplotlib change style
  • Add text to plot matplotlib mathematical formula
  • Add text box to plot matplotlib
  • Add text to bar plot matplotlib
  • Add text to scatter plot matplotlib
  • Add text to 3D plot matplotlib
  • Add text under plot matplotlib
  • Add text to top of plot matplotlib
  • Add text to bottom of plot matplotlib
  • Add text to right of plot matplotlib
  • Add text to corner of plot matplotlib
  • Add text to center of plot matplotlib
  • Add text to above plot matplotlib

If you are new to Matplotlib, check out What is Matplotlib and how to use it in Python and also, How to install matplotlib python

Add text to plot matplotlib

In this section, we are going to learn about how to add text to a plot in matplotlib. Before starting firstly, we understand what does “text” means.

Text is the written words that we want to add to the plot. We can add text for textual information or provide an explanation of the plot.

The following steps are used to add text in the plot in matplotlib are outlined below:

  • Defining Libraries: Import the important libraries which are required to add text in the plot (For data creation and manipulation: Numpy, For data visualization: pyplot from matplotlib).
  • Define X and Y: Define the data values used for the x-axis and y-axis.
  • Add text to the plot: By using the text() function we can easily add text to a graph.
  • Display: To show the graph we use the show() function.

The syntax to add text to a plot is as below:

matplotlib.pyplot.text(x, y, s, fontdict=None, **kwargs)

The above-used parameters are outlined as below:

  • x: specifies x coordinates position to place text.
  • y: specifies y coordinate position to place text.
  • s: specifies the text.
  • fontdict: a dictionary that specifies the text properties other than the default.
  • kwargs: specifies some other text properties.

Note: We can change the coordinate system by using transform parameter.

Check out, Python plot multiple lines using Matplotlib

Add text to plot matplotlib example

In the above section, we discussed what does text means and what are the various steps and we also learn the syntax to add text to the plot.

Let’s understand the concept of adding text more clearly with the help of an example:

# Import library

import matplotlib.pyplot as plt

# Define Data

x = [7, 14, 21, 28, 35]
y = [4, 8, 12, 16, 20]

# Plot a Graph

plt.plot(x, y, color = 'm')

# Add text

plt.text(7.8, 12.5, "I am Adding Text To The Plot")

# Display Graph

plt.show()
  • In the above example, we import the matplotlib.pyplot library and define the x and y axes data points.
  • We use plt.plot() method to plot a graph and after that we use plt.text() method to add text to the plot.
  • Here we pass arguments as x=7.8, y=12.5 and we pass the text ” I am Adding Text To The Plot ” which we want to print at specified axes.
  • Finally, we use the plt. show() to display the plot.
add text to plot matplotlib example
plt.text()

Check out, Matplotlib plot a line

Add multiple line text to plot matplotlib

Sometimes, we want to place more than one text note in our plot. So to add more than one line of text we need to add a new line symbol “\n”.

The syntax to add multiple texts is as below:

matplotlib.pyplot.text(x, y, "Text1 \n Text2 \n Text3 ... " )

The parameters used above are:

  • x and y: specifies the coordinates to place text.
  • Text1, Text2: specifies the multiple texts we want to add. In between Text we use new line symbol.

Let’s see the example related to multiple lines of text:

# Import library

import matplotlib.pyplot as plt

# Define Data


x = [7, 14, 21, 28, 35]
y = [4, 8, 12, 16, 20]

# Plot a Graph

plt.plot(x, y, color = 'r', linestyle= '--')

# Add multiple texts


plt.text(13, 18, "I am Adding Text To The Plot \nI am Trying To Add a New Line of Text \nWaoo! Mutiple Texts are added")

# Display Graph

plt.show()

In the above example, we use the text() method to add text to the plot and we pass the parameters x, y, and texts, and between the multiple texts we use “\n”.

add multiple line text to plot matplotlib
plt.text()

Check out, Matplotlib plot bar chart

Add text to plot matplotilb change style

Matplotlib provides us with a feature to change the style of the added text.

To change the style we have to pass a dictionary defining a new style to the parameter fontdict.

If you want to know about more styles and properties of text visit the official matplotlib page.

# Import library


import matplotlib.pyplot as plt

# Define Data

x = [7, 14, 21, 28, 35]
y = [4, 8, 12, 16, 20]

# Plot a Graph

plt.plot(x, y, color = 'r', linestyle= '--')

# Add dictionary

font = {'family': 'cursive',
        'color':  'k',
        'weight': 'bold',
        'size': 12,
        }

# Change text style

plt.text(7.5, 18, "Changing style and properties of    text",fontdict = font )

# Display Graph

plt.show()
  • In the above example, we create a dictionary defining a new style and properties to the text.
  • After that, we use the text() method to plot the text inside the graph and pass the paramter fontdict to change the styles.
add text to plot matplotlib change style
plt.text()

Also, check out, What is matplotlib inline

Add text to plot matplotlib mathematical formula

Many times we need to add mathematical formulas in the chart or graph. So text() method provides the feature of adding formula to the plot.

To add the formula we have to add a dollar symbol “$” at the start and end of the formula.

The syntax to add the mathematical formula:

matplotlib.pyplot.text(x, y, "$Formula$" )

Let’s see an example to understand how to add a formula to the chart:

# Import library

import matplotlib.pyplot as plt

# Define Data

x = [1, 2, 3, 4, 5]
y = [1, 2, 3, 4, 5]

# Plot a Graph

plt.plot(x)

# Mathematical Formula

plt.text(1,4, "$y=mx + c$",{'color':'green','weight':'heavy','size':20})

# Display Graph


plt.show()
  • In the above example, we import matplotlib.pyplot library.
  • After this, we define data on the x-axis and y-axis and we use plt.plot() method to plot a chart.
  • We use plt.text() method to add text to the plot, and we pass a special string “mathematical formula” to the method.
  • To print a string in the form of the formula we use the dollar symbol ” $ “ at the start and end of the string.
add text to matplotlib mathematical formula
plt.text() “Mathematical formula of straight line”

Check out, Matplotlib subplot tutorial

Add text box to plot matplotlib

We can decorate your text by placing it into a box. Matplotlib provides the functionality to change the style, color of the box also.

You can make your plot more attractive by adding a box around your text. The bbox keyword argument is used to place a text box.

The syntax to add a box:

matplotlib.pyplot.text(x,y,bbox={Create dict of bbox style})

The parameters used above are:

  • x and y: coordinates of data points
  • bbox: keyword to place box around the text. It takes a dictionary with keys that define the style of the box.

Let’s see an example of adding box around the text:

# Import library


import matplotlib.pyplot as plt

# Define Data

x = [1, 2, 3, 4, 5]
y = [1, 2, 3, 4, 5]

# Plot a Graph

plt.plot(x)

# Define bbox style

box_style=dict(boxstyle='round', facecolor='wheat', alpha=0.5)

# Text inside a box

plt.text(1.2,4.2, "$y=mx + c$",{'color':'red','weight':'heavy','size':20},bbox=box_style)

# Display Graph

plt.show()
  • In the above example, we use plt.text() method to add a text inside the chart and we pass the keyword argument bbox to place a text inside the box.
  • The style of the bbox is defined in the box_style variable.
add text box to plot matplotlib
plt.text(bbox)

Check out, Matplotlib plot error bars

Add text to bar plot matplotlib

To visualize the graphical data we can use Bar Chart, so we can easily compare the data by viewing the different heights of the bars.

For plotting the bar chart we use plt.bar() method and pass the x and y coordinates.

By default bar chart doesn’t display value labels of the bars and so, sometimes it becomes difficult the analyze the exact value of the bar.

By using the plt.text() method we can easily add the text labels on each bar of the bar chart.

The syntax to create a bar chart and adding labels to each bar is as follow:

# To create bar chart
matplotlib.pyplot.bar(x, height)

# To add text label 
matplotlib.pyplot.text(x, y, s , ha , va, bbox)

The parameters used above are defined as below:

  • x: specifies x coordinates of the bar.
  • height: specifies y coordinates of the bar.
  • x: specifies x coordinates of the text.
  • y: specific y coordinates of the text.
  • s: specifies the text to display.
  • ha: specifies the horizontal alignment
  • va: specifies the vertical alignment
  • bbox: specifies rectangular box around the text

Let’s take different examples to understand more clearly about the concept:

Example: By default bar chart

# Import Library

import matplotlib.pyplot as plt

# Define Data


student = [5, 10, 12, 16, 18]
marks= [99, 90, 80, 85, 75]

# Plot Graph

  
plt.bar(student,marks) 

# Define Labels


plt.xlabel("No.Of students")
plt.ylabel("Marks of students")

# Display Graph

plt.show()

In the above example, we simply plot the bar chart showing students and their marks. We use plt.bar() method to plot this bar chart.

We observe that by default bar chart doesn’t display the value of each bar.

add text to bar plot matplotlib
plt.bar()

Check, Matplotlib remove tick labels

Example: Adding text labels on the bar chart

# importing library

import matplotlib.pyplot as plt
  
# function to add text

def addtext(x,y):
    for i in range(len(x)):
        plt.text(i,y[i],y[i])

# Main function

if __name__ == '__main__':
    
    # Define data
    x = ["A","B","C","D","E","Fail"]
    y = [15, 12, 3, 5,1, 2]
      
    # Plot bar chart
    plt.bar(x, y)
      
    # Call function
    addtext(x, y)       
     
    # Define labels
    plt.xlabel("Grades")
    plt.ylabel("Number of Students")
      
    # Display plot
    plt.show()
  • In the above example, we import the library matplotlib.pyplot
  • Create a function addtext() that can add text to the bars. In the function, we use a for loop for the length of x value, and to calculate the length we use len() method.
  • After this we use plt.text() method to add the text on each bar and we pass i and y[i] which represent the height and the string to be print respectively.
  • We create the main function and define the data points.
  • Then by using plt.bar() we plot the bar chart and pass the coordinates x and y to it. And we also add labels on the x-axis and y-axis.
  • Finally, we use plt.show() method to display the plot.
add text to bar plot
plt.text()

Example: Adding text to the bar chart aligned in the center and having a box around the text

# Import library

import matplotlib.pyplot as plt
  
# Function to add text in center with box

def addtext(x,y):
    for i in range(len(x)):
        plt.text(i,y[i],y[i], ha = 'center',
                 bbox = dict(facecolor = 'pink', alpha =0.8))
        
# Main function
  
if __name__ == '__main__':
    
    # Define data
    x = ["A","B","C","D","E","Fail"]
    y = [15, 12, 3, 5,1, 2]
      
    # Plot bar chart
    plt.bar(x, y)
      
    # Call function
    addtext(x, y)       
     
    # Define labels
    plt.xlabel("Grades")
    plt.ylabel("Number of Students")
      
    # Display plot
    plt.show()
  • In the above example, we import the library matplotlib.pyplot.
  • We create a function addtext() that can add text to the bars. In the function, we use a for loop for the length of x value, and to calculate the length we use len() method and we pass horizontal alignment parameter and set it center.
  • We also pass bbox arguement to text() method and define dictionary having style of box.
  • After this we use plt.text() method to add the text on each bar and we pass i and y[i] which represent the height and the string to be print respectively.
  • We create the main function and define the data points.Then by using plt.bar() we plot the bar chart and pass the coordinates x and y to it. And we also add labels on the x-axis and y-axis.
  • Finally, we use plt.show() method to display the plot.
add text to bar plot matplotlib having bbox
plt.text(ha=’center’,bbox=dict())

Read Matplotlib rotate tick labels

Example: Add text to the bar chart at the center of the height and also add a box around to the text

# Import library


import matplotlib.pyplot as plt
  
# Function to add text in center with box


def addtext(x,y):
    for i in range(len(x)):
        plt.text(i,y[i]//2,y[i], ha = 'center',
                 bbox = dict(facecolor = 'red', alpha =0.8))
        
# Main function
  
if __name__ == '__main__':
    
    # Define data
    x = ["A","B","C","D","E","Fail"]
    y = [15, 12, 3, 5, 0, 2]
      
    # Plot bar chart
    plt.bar(x, y,color='yellow')
      
    # Call function
    addtext(x, y)       
     
    # Define labels
    plt.xlabel("Grades")
    plt.ylabel("Number of Students")
      
    # Display plot
    plt.show()

In the above example, we add the text box inside the center of each bar. For doing so, we divide the y coordinates by 2 and we pass the values in the addtext() function.

add text to center of bar s
plt.text()

Read Matplotlib change background color

Add text to scatter plot matplotlib

We can add text to the scatter plots in matplotlib.

The syntax to create a scatter plot and add text is as below:

# Create scatter plot
matplotlib.pyplot.scatter(x,y)

# Add text
matplotlib.pyplot.text(x,y)
  • Here x and y parameters of scatter() method represent x and y coordinates of data points.
  • And x and y parameter of the text() method represents the x-axis and y-axis point of the text.

Let’s see an example of adding text to a scatter plot:

# Importing library


import matplotlib.pyplot as plt
  
# Define data


x = [3.5, 2, 3, 4, 5]
y = [2.6, 1, 1.5, 2, 2.6]

annotations=["P1","P2","P3","P4","P5"]
      
# Plot scatter

plt.scatter(x, y,color='black') 

plt.xlabel("X")
plt.ylabel("Y")

# add text

for i, label in enumerate(annotations):
    plt.text(x[i], y[i],label,ha='right',size=12,color= 'red') 
    
# Display plot

plt.show()
  • In the above example, we use plt.scatter() method and we pass x and y data points.
  • Then we use plt.text() method to add text on the scatter points.
add text to scatter plot matplotlib
The output to add text in scatter plot

Read Matplotlib scatter marker

Add text to 3D plot matplotlib

In this section, we are going to study how to draw a 3D plot and how we can add text to it.

The syntax to create a 3D plot and adding text:

# Create 3D plot
ax.plot3D(x,y,z)
# Add text
ax.text(x,y,z)

Here x, y, and z are the coordinates points.

Let’s see an example related to this:

# Import Library

from mpl_toolkits import mplot3d
import matplotlib.pyplot as plt
 
fig = plt.figure()
 
# 3D projection

ax = plt.axes(projection ='3d')
 
# Define axes

z = [0, 1, 2, 3]
x = [4, 5, 6, 7]
y = [1, 8, 9, 5]
 
# plotting

ax.plot3D(x, y, z, 'green')

# add text


ax.text(4, 4,1, "plot a point")

# display graph

plt.show()
  • In the above, example, we import mplot3d and matplot.pyplot library.
  • After this, we define 3D projection and 3D data points, and by using plot3D() method we create a 3D plot.
  • text() method is used to add text at a specific position and show() method is used to visualize the plot.
add text to 3d plot matplotlib
plt.text()

Read Matplotlib dashed line

Add text under plot matplotlib

Here we learn to add text under the plot in matplotlib. We use the figtext() method to add text in the figure area and we set the horizontal and vertical alignment at the center.

Let’s see an example and learn how to plot text to the bottom:

# Import Library

import matplotlib.pyplot as plt

plt.clf() # Clear the figure

# Define data

x = [2, 4, 8]
y = [5, 10, 15]


# Plot graph

plt.plot(x,y,'o')

# text

plt.figtext(0.5,0.01, "Text under the Plot", ha="center", va="center", fontsize=18, bbox={"facecolor":"orange", "alpha":0.5})


# Plot graph

plt.show()
  • In this above example, we add the text under the plot by using the fig.text() method and we pass the argument x = 0.5 and y=0.01.
  • We set the alignment of the text box in the center.
add text under plot matplotlib
plt.figtext()

Read Matplotlib plot_date

Add text to top of plot matplotlib

Here we will learn how we add text on the top of the plot.

Let’s see an example to add text to the left-top of the plot:

# import library

import matplotlib.pyplot as plt

# Define axes

left = 0.01
width = 0.9
bottom  = 0.01
height = 0.9
right = left + width
top = bottom + height
ax = plt.gca()

# Transform axes

ax.set_transform(ax.transAxes)

# Define text

ax.text(left, top, 'left top',
        horizontalalignment='left',
        verticalalignment='top',color='r',size=10,
        transform=ax.transAxes)

# Display Graph

plt.show()
  • In the above example, we define the data, and then we use the transform() method.
  • After this, we plot the text on the left top of the plot by using an ax.text() method
  • Here we set horizontal alignment to the “left” and vertical alignment to the “top”.
add text to left plot matplotlib
“Top”

Read Matplotlib log log plot

Add text to bottom of plot matplotlib

In this section, we will see an example of add text at bottom of the plot.

The bottom of the plot means in the lowest position.

Let’s see an example to add text to the left-bottom of the plot:

# import library

import matplotlib.pyplot as plt

# Define axes

left = 0.01
width = 0.9
bottom  = 0.01
height = 0.9
right = left + width
top = bottom + height
ax = plt.gca()

# Transform axes

ax.set_transform(ax.transAxes)

# Define text


ax.text(left, bottom, 'left bottom',
        horizontalalignment='left',
        verticalalignment='bottom',
        color='r',size=10,
        transform=ax.transAxes)

# Display Graph

plt.show()

Here we plot the text on the left bottom of the plot by using an ax.text() method and we set horizontal alignment to the “left” and vertical alignment to the “bottom”.

add text to bottom of the plot matplotlib
“Bottom”

Read Matplotlib subplots_adjust

Add text to right of plot matplotlib

Here we will see how we can write text on the right-hand side of the plot.

Let’s see an example for better understanding:

# import library

import matplotlib.pyplot as plt

# Define axes

left = 0.01
width = 0.9
bottom  = 0.01
height = 0.9
right = left + width
top = bottom + height
ax = plt.gca()

# Transform axes

ax.set_transform(ax.transAxes)

# Define text

ax.text(right, top, 'Right Side of the Plot',
        horizontalalignment='right',
        verticalalignment='top',
        color='g',size=15,
        transform=ax.transAxes)

# Display Graph

plt.show()

Here we plot the text on the right side of the plot by using an ax.text() method and we set horizontal alignment to the “right” and vertical alignment to the “top”.

add text to right of plot matplotlib
“Right Side”

Read Matplotlib best fit line

Add text to corner of plot matplotlib

The corner is the side where two edges meet. We have to set the axes of text at the corner according to our suitability.

Here is the example of text aligned at the corner:

# import library

import matplotlib.pyplot as plt

# Define axes

left = 0.01
width = 0.9
bottom  = 0.01
height = 0.9
right = left + width
top = bottom + height
ax = plt.gca()

box_style=dict(boxstyle='round', facecolor='wheat', alpha=0.5)

# Transform axes


ax.set_transform(ax.transAxes)

# Define text

ax.text(0.99, 0.8 , 'Corner',
        horizontalalignment='right',
        rotation='vertical',
        bbox=box_style,
        size=12,
        color='blue',
        transform=ax.transAxes)

# Display Graph

plt.show()
  • Firstly, we import the libraries and define the data, then we use the transform() method.
  • After this, we plot the text at the corner of the plot by using an ax.text() method.
  • Here we set horizontal alignment to the “right” and we add some extra features.
add text to corner of plot matplotlib
“Corner”

Read Matplotlib save as pdf

Add text to center of plot matplotlib

The middle of the plot is known as the center position. Here we set the text between the center of left, right, bottom, and top position or we can say that exactly in the middle of the plot.

Let’s see an example:

# import library

import matplotlib.pyplot as plt

# Define axes

left = 0.01
width = 0.9
bottom  = 0.01
height = 0.9
right = left + width
top = bottom + height
ax = plt.gca()

# Transform axes

ax.set_transform(ax.transAxes)

# Define text

ax.text(0.5 * (left + right), 0.5 * (bottom + top), 'I am at the center',
        horizontalalignment='center',
        verticalalignment='center',
        size= 12,
        color='r',
        transform=ax.transAxes)

# Display Graph

plt.show()
  • Here we use the ax.text() method to add the text at the middle of the plot.
  • We set the horizontal and vertical alignment at the center of the plot.
  • We also define the position of the text by finding the middle of the left and right and also of the bottom and top.
add text to center of the plot matplotlib
“Center”

Read Matplotlib set_xticks

Add text above plot matplotlib

In this section, we learn to add text above the plot in matplotlib. The figtext() method is used to add text in the figure area.

Here we set the horizontal and vertical alignment at the center.

Let’s see an example to add text above the plot:

# Import Library


import matplotlib.pyplot as plt


plt.clf()     # Clear the current figure


# Define data

x = [2, 4, 8]
y = [5, 10, 15]


# Plot graph

plt.plot(x,y,'o')

# text

plt.figtext(0.5,1, "Text above the Plot", ha="center", va="center", fontsize=18, bbox={"facecolor":"r", "alpha":0.5})


# Plot graph

plt.show()
  • Here we import the matplotlib.pyplot library and after this to clear the figure we use the clf() method.
  • We define the data point and plot them by using the plot() method in the scatter style.
  • plt.figtext() method is used to add text above the plot and here we set x-axis= 0.5 and y-axis = 1.
  • Finally, we use the show() method to visualize the plot.
add text above plot matplotlib
“Above the plot”

In this Python tutorial, we have discussed the “Add text to plot matplotlib” and we have also covered some examples related to it. These are the following topics that we have discussed in this tutorial.

  • Add text to plot matplotlib
  • Add text to plot matplotlib example
  • Add mutiple line text to plot matplotlib
  • Add text to plot matplotlib change style
  • Add text to plot matplotlib mathematical formula
  • Add text box to plot matplotlib
  • Add text to bar plot matplotlib
  • Add text to scatter plot matplotlib
  • Add text to 3D plot matplotlib
  • Add text under plot matplotlib
  • Add text to top of plot matplotlib
  • Add text to bottom of plot matplotlib
  • Add text to right of plot matplotlib
  • Add text to corner of plot matplotlib
  • Add text to center of plot matplotlib
  • Add text to above plot matplotlib