Matplotlib place y axis on the right with flipped label

Viewed 794

I want to have the y axis on the right hand side of my plot, but also have the label facing the correct direction. There's many answers that explain the first part, which can be done as follows:

import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot()
ax.plot([1,2,3,4,5])
ax.set_ylabel("RHS")
ax.yaxis.set_label_position("right")
ax.yaxis.tick_right()
plt.show()

Which produces the following: enter image description here

But the issue here is the yaxis label on the right hand side is facing outwards, and ideally I would like it to face inwards, something like the following:

enter image description here

Any help with this would be much appreciated!

1 Answers

Just add the following kwargs to your set_ylabel call:

ax.set_ylabel("RHS",rotation=-90,labelpad=15)

which gives the intended output:

output

If you want to modify label after it has been set, alternatively you can do something like:

yl = ax.set_ylabel("RHS")
ax.yaxis.set_label_position("right")
yl.set_rotation(50)
# do some other stuff

then don't forget to call plt.draw() to make it effective. You may want to have a look at matplotlib text instance properties.

Related