2

The code below draws a plot that looks almost exactly the way I want it to be. However, I'd like the ylabel to be horizontal and left-aligned with the yticks. Currently, the ylabel is placed left relative to the yticks which looks ugly (the image below shows the upper left corner of the plot). Does someone know how to fix this?

import matplotlib.pyplot as plt
import numpy as np

xvals = range(0,10);
yvals = lambda s: [ x*x*s for x in xvals ]

# setting the x=... option does NOT help
yprops = dict(rotation=0, y=1.05, horizontalalignment='left')

plt.subplot(111,axisbg='#BBBBBB',alpha=0.1)
plt.grid(color='white', alpha=0.5, linewidth=2, linestyle='-', axis='y')

for spine_name in ['top', 'left', 'right']:
    plt.gca().spines[spine_name].set_color('none')

plt.ylabel('y label', **yprops)
plt.xlabel('x label')

plt.gca().tick_params(direction='out', length=0, color='k')

plt.plot(xvals, yvals(1), 'bo-', linewidth=2)
plt.gca().set_axisbelow(True)

plt.show()

enter image description here

dsd
  • 551
  • 5
  • 17

1 Answers1

0

You can adjust the coordinates using ax.yaxis.set_label_coords like in this example.

With your data:

import matplotlib.pyplot as plt
import numpy as np

xvals = range(0,10);
yvals = lambda s: [ x*x*s for x in xvals ]

yprops = dict(rotation=0, x=0, y=1.05)

fig, ax = plt.subplots(1, 1, figsize=(5,3))

ax.set_ylabel('y label', **yprops )
ax.set_xlabel('x label')
ax.plot(xvals, yvals(1), 'bo-', linewidth=2)

print(ax.get_position())
ax.yaxis.set_label_coords(-0.1,1.05)

fig.savefig('cucu.png')

plt.show()

enter image description here


Note that if you go further away, the label will be placed outside the figure. If that is the case, you can adjust the margins before:

fig, ax = plt.subplots(1, 1, figsize=(5,3))

ax.set_ylabel('y label', **yprops )
ax.set_xlabel('x label')
ax.plot(xvals, yvals(1), 'bo-', linewidth=2)

fig.subplots_adjust(left=0.2, bottom=0.2, right=0.8, top=0.8)
ax.yaxis.set_label_coords(-0.2,1.2)

fig.savefig('cucu2.png')

plt.show()

enter image description here


See also this answer

Community
  • 1
  • 1
Luis
  • 3,327
  • 6
  • 35
  • 62