Matplotlib使用翻转标签将y轴放置在右侧

2024-06-28 20:16:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我希望y轴位于绘图的右侧,但标签也朝向正确的方向。有许多答案可以解释第一部分,具体如下:

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()

这将产生以下结果: enter image description here

但这里的问题是,右边的yaxis标签朝外,理想情况下,我希望它朝内,如下所示:

enter image description here

在此方面的任何帮助都将不胜感激


Tags: 答案importright绘图matplotlibasfigplt
1条回答
网友
1楼 · 发布于 2024-06-28 20:16:59

只需将以下KWARG添加到set_ylabel调用中:

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

给出了预期输出:

output

如果要在设置标签后修改标签,也可以执行以下操作:

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

然后别忘了调用plt.draw()使它生效。您可能需要查看matplotlib text实例属性

相关问题 更多 >