2

We can specify the position of text in PyPlot, but how can we read the position of text? For example, I want to know the coordinates of the Figure's title or the Axes X and Y labels.

Pseudo-code:

x, y = PyPlotObject.get_position()

I'm also interested in related text properties such as size, scale and rotation.

import matplotlib.pyplot as plt
import numpy as np

x1 = np.linspace(0.0, 5.0, 100)
y1 = np.cos(2 * np.pi * x1) * np.exp(-x1)

fig, ax = plt.subplots(figsize=(5, 3))
fig.subplots_adjust(bottom=0.15, left=0.2)
ax.plot(x1, y1)
ax.set_xlabel('Time (s)')
ax.set_ylabel('Damped oscillation (V)')
ax.set_title('Oscillation')

plt.show()
3
  • This command ax.xaxis.get_label().get_position() will give you the following output: (0.5, 15.72222222222223). Here we see the 0.5 on the x axis (in the middle of the plot). But for the Y coordinate we see something else, I am guessing this is a value that is in another axis coordinate. To transform the 15.7 to a value that is between 0-1, I think you would need to see what the renderer is doing Commented Oct 14 at 8:55
  • Thanks! That works for an axis label. But what's the corresponding method for a Figure.title? Commented Oct 14 at 16:19
  • I think it's just ax.title.get_position(). Commented Oct 14 at 23:20

1 Answer 1

1

You are already using the so-called 'object oriented' interface for Matplotlib, which is a good start. Once you have made the plot in your example, you can get at its objects, and then at their properties.

For example:

xlabel = ax.xaxis.get_label()
xlabel.get_position()

Yields (0.5, np.float64(24.0)). If you explore this xlabel object, you can see the object contains the position and the text, as well as other things like font size — try xlabel.get_fontsize() or xlabel.get_rotation().

You can get at the title's properties in a similar way, e.g. position:

ax.title.get_position()
Sign up to request clarification or add additional context in comments.

1 Comment

Do you know by any chance what the 24.0 is? I tested around a bit and it seems to change with the length of the labels. The 0.5 is basically the relative position of the label compared to the start (0.5 -> 50% -> middle of the figure). I played around yesterday with fig.canvas.get_renderer() and could eventually get some values.. not sure however if that's what OP wants

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.