117

I'm creating very simple charts with matplotlib / pylab Python module. The letter "y" that labels the Y axis is on its side. You would expect this if the label was longer, such as a word, so as not to extend the outside of the graph to the left too much. But for a one-letter label, this doesn't make sense; the label should be upright.

How can I show the "y" horizontally?

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
Karl D
  • 1,295
  • 2
  • 8
  • 5

3 Answers3

154

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()
Nico Schlömer
  • 53,797
  • 27
  • 201
  • 249
Jens Munk
  • 4,627
  • 1
  • 25
  • 40
132

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

Evgeni Sergeev
  • 22,495
  • 17
  • 107
  • 124
  • 60
    for better clarity you might consider `rotation='horizontal'`. Also, instead of choosing an arbitrary `labelpad` (and then needing to adjust based on results), you can add the argument `ha='right'`, where `ha` is a convenient abbreviation for the `horizontalalignment` keyword. – NauticalMile Mar 14 '17 at 16:02
  • 11
    And `va="center"` for `verticalalignment`. – jds May 08 '20 at 14:47
  • 1
    How to set the orientation without changing existing labels? This is required when the labels have been set by say an external module `librosa.display.specshow()`. – mins Apr 02 '21 at 21:06
2

Axes object defines yaxis (and xaxis) which has label property which can be changed using set() method. So for example, to change rotation, horizontal alignment etc. of the y-label, the following can be used:

ax.yaxis.label.set(rotation='horizontal', ha='right');

This is especially useful if the graph is plotted using an external module such as librosa, perfplot etc. where the y-label is set under the covers of the module and you want to rotate it.

x = y = range(3)
plt.plot(x, y)
plt.ylabel('y label')

plt.gca().yaxis.label.set(rotation='horizontal', ha='right');

result

cottontail
  • 10,268
  • 18
  • 50
  • 51