Issue
I have this example:
from numpy import linspace, sin
from matplotlib.pyplot import plot, ylabel, gcf, text
x = linspace(0, 1)
y = x ** 2
plot(x, y)
ylabel("test")
I now want to place some text approximately like "abc" in this figure:
For this, I need the x coordinate of the y-label, or at least approximately. I tried the following:
xd, _ = pyplot.gca().yaxis.get_label().get_transform().transform((0, 0))
But it seems that xd
is now always 0 in display coordinates. That is clearly not correct. Furthermore, if I want to transform it back to figure coordinates to display the text:
x, _ = gcf().transFigure.inverted().transform_point((xd, 0))
text(0, 0.5, "abcdefg", transform=gcf().transFigure)
I get this:
So clearly, the x coordinate is not correct.
Solution
Combining the discussion into an answer:
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.set_ylabel("test")
# draw the elements
fig.draw_without_rendering()
# get the position of the ylabel and transform it to coordinates
pos_pixel = ax.yaxis.label.get_tightbbox()
x_coord = ax.transData.inverted().transform((pos_pixel.x0, pos_pixel.y0))[0]
plt.text(x_coord, 0.42, "abc", color="red")
plt.show()
Answered By - Christian Karcher
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.