简体   繁体   中英

Matplotlib place y axis on the right with flipped label

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: 在此处输入图片说明

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:

在此处输入图片说明

Any help with this would be much appreciated!

Just add the following kwargs to your set_ylabel call:

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

which gives the intended 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM