Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define ylabel position relative to axis with matplotlib?

I need to precisely control the position of my ylabel independently of my yticklabels with matplotlib. This is because I have a matplotlib animation that currently has the ylabel jumping around as I change yticklabels. This is undesirable.

The docs seem to only allow me to specify distance from the leftmost part of my yticklabels. (which does not solve the problem, and indeed is causing it)

One solution would be to manually put the label. But is there a simpler way?

like image 339
gota Avatar asked May 08 '20 17:05

gota


1 Answers

You can emulate the behavior of a normal y-label by adding text explicitly to the axes. If the y-limits are changing quite a bit, this is best done by placing the text in axes coordinates, rather than data coordinates. This is done with the transform keyword-argument, like so:

import matplotlib.pyplot as plt
fig, ax = plt.subplots()
t = ax.text(-0.1, 0.5, 'Y label', rotation=90, 
            verticalalignment='center', horizontalalignment='right', 
            transform=ax.transAxes)
ax.set_ylim(-10, 10) # Change y-limits, label position won't change.

This places the text halfway up the axes, and slightly to the left. Changes to the data limits of the axes have no effect on the text, as it is always defined in axes coordinates. Similarly, scaling the plot or axes (resizing the window with the mouse, using fig.set_size_inches, etc) will keep the y-label in position relative to the axes box itself, exactly what you want for a label.

You may have to play with the x-position of the label, to make sure it doesn't overlap the tickmarks as they change during animation.

like image 138
bnaecker Avatar answered Oct 04 '22 15:10

bnaecker