Write a text inside a subplot

13,875

Without more code details, it's quite hard to guess what is wrong.

The matplotlib.axes.Axes.text works well to show text box on subplots. I encourage you to have a look at the documentation (arguments...) and try by yourself.

The text location is based on the 2 followings arguments:

  • transform=ax.transAxes: indicates that the coordinates are given relative to the axes bounding box, with (0, 0) being the lower left of the axes and (1, 1) the upper right.
  • text(x, y,...): where x, y are the position to place the text. The coordinate system can be changed using the below parameter transform.

Here is an example:

# import modules
import matplotlib.pyplot as plt
import numpy as np

# Create random data
x = np.arange(0,20)
y1 = np.random.randint(0,10, 20)
y2 = np.random.randint(0,10, 20) + 15

# Create figure
fig, (ax1,ax2) = plt.subplots(nrows=2, ncols=1, figsize = (12,7), tight_layout = True)

# Add subplots
ax1.plot(x, y1)
ax1.plot(x, y2)
ax2.plot(x, y1)
ax2.plot(x, y2)

# Show texts
ax1.text(0.1, 0.5, 'Begin text', horizontalalignment='center', verticalalignment='center', transform=ax1.transAxes)
ax2.text(0.9, 0.5, 'End text', horizontalalignment='center', verticalalignment='center', transform=ax2.transAxes)

plt.show()

output

enter image description here

Share:
13,875
SosaAlmighty
Author by

SosaAlmighty

Updated on July 10, 2022

Comments

  • SosaAlmighty
    SosaAlmighty almost 2 years

    I'm working on this plot:

    enter image description here

    I need to write something inside the first plot, between the red and the black lines, I tried with ax1.text() but it shows the text between the two plots and not inside the first one. How can I do that?

    The plot was set out as such:

    fig, (ax1,ax2) = plt.subplots(nrows=2, ncols=1, figsize = (12,7), tight_layout = True)
    

    Thank you in advance for your help!

  • SosaAlmighty
    SosaAlmighty about 4 years
    Thank you I needed that "transform" arg!
  • VjayalakshmiK
    VjayalakshmiK over 2 years
    What does the 'transform' argument do?
  • Alexandre B.
    Alexandre B. over 2 years
    @VjayalakshmiK Have a look at the updated answer