pythonmatplotlibplot

How to align top-rotated ylabel on the righthand side on a plot with matplotlib


In matplotlib, how can I get the y-label to align with the top of the plot, when the label is rotated, moved to the right and top?

import matplotlib.pyplot as plt
import numpy as np

#create plot
fig, ax = plt.subplots()
ax.plot(np.sin(np.linspace(-np.pi, np.pi, 1001)))

ax.tick_params(
                    which="both",
                    direction="out",
                    left=False,
                    right=True,
                    labelleft=False,
                    labelright=True,
                )

ax.set_ylabel("y-label", loc="top", rotation=-90, labelpad=10)
ax.yaxis.set_label_position("right")

matplotlib example


Solution

  • You could fix the horizontal alignment after defining the label (unfortunately, you can't define it directly in set_ylabel if loc is used):

    ax.set_ylabel('y-label', loc='top', rotation=-90, labelpad=10)
    ax.yaxis.set_label_position('right')
    ax.yaxis.label.set_horizontalalignment('left')
    

    Output:

    enter image description here