Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Position font relative to axis using ax.text, matplotlib

I'm not sure how to properly position font relative to an axis object using matplotlib.

Example:

fig, axes = plt.subplots(nrows=1, ncols=3, figsize=(10, 4), dpi=100)
x = [1, 2]
y = [3, 4]

y_loc = 4.1
x_loc = 0.95
fs = 12
ax = axes[0]
ax.plot(x, y)
_ = ax.text(x=x_loc, y=y_loc, s="Plot 1", fontsize=fs)

ax = axes[1]
ax.plot(x, y)
_ = ax.text(x=x_loc, y=y_loc, s="Plot 2", fontsize=fs)

ax = axes[2]
_ = ax.plot(x, y)
_ = ax.text(x=x_loc, y=y_loc, s="Plot 3", fontsize=fs)

Which gives:

enter image description here

The use of values:

y_loc = 4.1
x_loc = 0.95

makes me think that there should be a better approach to this.

Note - I would like to use ax.text here, not title, and the question is mainly about how best to position text relative to a particular axis within a subplot. Ideally it would extend to a grid plot as well if it was just relative to a particular axis.

like image 491
baxx Avatar asked Sep 02 '26 23:09

baxx


1 Answers

Default, ax.text uses "data coordinates", i.e. with x and y as shown on the ticks of the axes. To plot relative to the rectangle defined by the axes, use transform=ax.transAxes. Here 0,0 will be the point at the bottom left and 1,1 the point at the top right. (This kind of coordinates is also very useful when positioning a legend.)

from matplotlib import pyplot as plt
import numpy as np

fig, axes = plt.subplots(nrows=1, ncols=3, figsize=(10, 4), dpi=100)

for ind, ax in enumerate(axes):
    ax.plot(np.random.randint(0, 10, 2), np.random.randint(0, 10, 2))
    ax.text(x=0, y=1.05, s=f"Plot {ind+1}", fontsize=12, transform=ax.transAxes)
plt.show()

example plot

like image 158
JohanC Avatar answered Sep 04 '26 11:09

JohanC



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!