Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write a text inside a subplot

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!

like image 883
SosaAlmighty Avatar asked Dec 13 '22 08:12

SosaAlmighty


1 Answers

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

like image 184
Alexandre B. Avatar answered Dec 18 '22 06:12

Alexandre B.