如何在 matplotlib/pylab 图表中水平打印 Y 轴标签?

我正在使用 matplotlib/pylab Python 模块创建非常简单的图表。标记 Y 轴的字母“ y”在它的侧面。如果标签比较长(比如一个单词) ,您就会预料到这一点,这样就不会将图的外部向左扩展太多。但对于一个字母的标签,这是没有意义的,标签应该是正确的。我的搜索一无所获。如何水平打印“ y”?

115311 次浏览

It is very simple. After plotting the label, you can simply change the rotation:

import matplotlib.pyplot as plt


plt.ion()
plt.plot([1, 2, 3])


plt.ylabel("y", rotation=0)
# or
# h = plt.ylabel("y")
# h.set_rotation(0)


plt.draw()

Expanding on the accepted answer, when we work with a particular axes object ax:

ax.set_ylabel('abc', rotation=0, fontsize=20, labelpad=20)

Note that often the labelpad will need to be adjusted manually too — otherwise the "abc" will intrude onto the plot.

From brief experiments I'm guessing that labelpad is the offset between the bounding box of the tick labels and the y-label's centre. (So, not quite the padding the name implies — it would have been more intuitive if this was the gap to the label's bounding box instead.)