18

I am trying to add some text to a figure that I would like to align with thexlabelof the axes. I want to find the coordinates of thexlabel, but the functionax.get_xlabel()only returns the string displayed in the label.

How can I get access to thexlabelobject (which I assume is just an instance of text) to find its coordinates, or is there some other means of obtaining them?

user3419537
  • 4,740
  • 2
  • 24
  • 42
  • Pretty sure that's in the docs with examples. – wwii Jul 18 '14 at 14:29
  • @wwii well if you'd like to point me to where I could find it that would be great. The only functions I have found in the docs are `set_xlabel()` and `get_xlabel()` which only operate on the string value – user3419537 Jul 18 '14 at 14:39
  • Start at the beginning of the [Artist Tutorial](http://matplotlib.org/users/artists.html), there is a hint to your solution right at the beginning. This is worth knowing if you want to have finer control over your Figures and/or you are going to be using matplolib a lot. – wwii Jul 18 '14 at 14:59
  • Ohhh, well now I feel stupid. I forgot that the "set" functions return a reference to the object. I also found I can get at it using `ax.xaxis.get_label()`. Thanks! – user3419537 Jul 18 '14 at 15:07
  • Quick search helps sometimes too, the (my) first result of a google search for "matplolib get xlabel position" turned up http://stackoverflow.com/questions/9290938/how-to-set-my-xlabel-at-the-end-of-xaxis – wwii Jul 18 '14 at 15:10
  • @wwii I saw that one (and several others) before posting, but it seems I missed the clues in the answer – user3419537 Jul 18 '14 at 15:19
  • possible duplicate of [Getting an object in Python Matplotlib](http://stackoverflow.com/questions/18102423/getting-an-object-in-python-matplotlib) – Engineer2021 Jul 18 '14 at 16:10

1 Answers1

31

The solution is not to use ax.get_xlabel(), but:

xlbl = ax.xaxis.get_label()

Or as wwii pointed out, just save a reference to the label when creating it. Embarrasingly simple.

xlbl = ax.set_xlabel(...)

and to obtain the coordinates:

xlbl.get_position()
user3419537
  • 4,740
  • 2
  • 24
  • 42
  • Why is this being downvoted? It answers the question. – user3419537 Jul 18 '14 at 16:31
  • you might get downvoted (not me), because your answer does not show *how exactly* you now get the coordinates (which is what you asked). maybe you could show how you extract the coordinates from `xlbl` (to get an upvote, maybe show how to change them subsequently) – Schorsch Jul 18 '14 at 19:45
  • Thanks @Schorsch, I guess the way I worded my question makes it sound that way. The emphasis was intended to be on finding the object since I already knew how to obtain its coordinates. I'll add it for completeness, but I still don't think that the downvote was justified. – user3419537 Jul 18 '14 at 23:19