Boris Gorelik
Boris Gorelik

Reputation: 31817

Proper alignment of labels in matplotlib

I don't like vertical labels for Y axis. Thus, I tend to do:

plt.ylabel('horizontal label', 
      rotation=0)

Which results in a nice label:

one-line label

However, if the required label contains more than one lines, the results is suboptimal:

plt.ylabel('horizontal\nmultiline label', 
     rotation=0, ha='right')

Multiline label

Changing to ha='left' doesn't do the right job

bad alignment

Is there a simple way to achieve this:

enter image description here

Upvotes: 3

Views: 3944

Answers (2)

ali_m
ali_m

Reputation: 74262

You can use the multialignment (ma=) parameter:

set_multialignment(align)

Set the alignment for multiple lines layout. The layout of the bounding box of all the lines is determined by the horizontalalignment and verticalalignment properties, but the multiline text within that box can be

ACCEPTS: [‘left’ | ‘right’ | ‘center’ ]

plt.ylabel('horizontal\nmultiline label', ha='right', va='center', ma='left',
           rotation=0)
plt.tight_layout()

enter image description here

Upvotes: 10

jonchar
jonchar

Reputation: 6482

You can use the set_label_coords() method of the ax.yaxis to define the (x, y) location of the label. You'll also probably want to use the va keyword argument as well. Putting them together you'd have:

fig, ax = plt.subplots()
ax.set_ylabel('horizontal\nmultiline label', rotation=0, ha='left', va='center')
ax.yaxis.set_label_coords(-0.25, 0.5)

Which should output this:

horizontal_label.png

Adjust the values passed to set_label_coords() as desired.

Upvotes: 1

Related Questions