Search code examples
pythonmatplotlibaxis-labels

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


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?


Solution

  • As of v3.3 you can now set these with the loc argument of set_xlabel and set_ylabel:

    import matplotlib.pyplot as plt
    
    # Left plot
    options = ['left', 'center', 'right']
    fig, axs = plt.subplots(len(options), 1, constrained_layout=True)
    
    for ax, loc in zip(axs, options):
        ax.plot([1, 2, 3])
        ax.set_xlabel(f'xlabel loc={loc!r}', loc=loc)
    
    # Right plot
    options = ['bottom', 'center', 'top']
    fig, axs = plt.subplots(1, len(options), constrained_layout=True)
    
    for ax, loc in zip(axs, options):
        ax.plot([1, 2, 3])
        ax.set_ylabel(f'ylabel loc={loc!r}', loc=loc)
    
    enter image description here enter image description here