Alessandro Jacopson
Alessandro Jacopson

Reputation: 18665

Is it possible to align different parts of an x label in different ways in matplotlib?

In matplotlib, is it possible to get and xlabel like the following one:

+--------------------+
|                    |
|                    |
|                    |
|                    |
|                    |
+--------------------+
L       center       R

I mean, L should be left aligned (to the begin of the axis), center should be centered and R should be right aligned (to the end of the axis).

Right now I get the number of spaces n1 and n2 by trial and error:

set_xlabel('L'+(' '*n1)+'center'+(' '*n2)+'R')

Upvotes: 0

Views: 81

Answers (1)

Karina
Karina

Reputation: 1280

Using plt.text

fig, ax = plt.subplots()
ax.set_xlabel('center')
plt.text(0.12, 0.035, 'L', transform=plt.gcf().transFigure)
plt.text(0.90, 0.035, 'R', transform=plt.gcf().transFigure)

enter image description here

Using ax.twiny

fig, ax = plt.subplots()
ax.set_xlabel('center')

xmin, xmax = ax.get_xlim()
axL = ax.twiny()
axL.xaxis.set_ticks_position('bottom')
axL.xaxis.set_label_position('bottom')
axL.set_xlabel('L', loc='left')
axL.set_xticks([xmin, xmax])
axL.set_xticklabels([' ', ' '])
axR = ax.twiny()
axR.xaxis.set_ticks_position('bottom')
axR.xaxis.set_label_position('bottom')
axR.set_xlabel('R', loc='right')
axR.set_xticks([xmin, xmax])
axR.set_xticklabels([' ', ' '])

enter image description here

Upvotes: 1

Related Questions