How to align axis label to the right or top in matplotlib?

Ruggero Turra picture Ruggero Turra · Jul 4, 2016 · Viewed 21.2k times · Source

By default matplotlib plots the axis label at the center of the axis. I would like to move the label in such way that it is aligned with the end of the axis, both for the horizontal and vertical axis. For example for the horizontal axis I would like to see:

+--------------------+
|                    |
|                    |
|                    |
|                    |
|                    |
+--------------------+
                 label

Is it possibile to do it with the global setting of matplotlib?

Answer

gboffi picture gboffi · Jul 4, 2016

My other answer is still a good one, because the idea of getting an object, modifying it and setting it back is a good idea on its own, but here it is an alternative, cleaner solution:

...
plt.xlabel('x_description', horizontalalignment='right', x=1.0)
plt.ylabel('y_description', horizontalalignment='right', y=1.0)
...

as you can see, no more magic numbers, and works both for xlabel and ylabel.

Note that in both cases we are going to change the horizontal alignment, for reasons that were eventually clear to me when I first changed the vertical alignment in ylabel...