-2

I have a stack of four vertical subplots. How do I display the x axis label and tick labels below the third subplot (i.e., on top of the fourth one)? This does not work:

import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots(4)
fig.subplots_adjust( hspace=0.0)  #I can't remove this. Not negotiable. :(

x = np.arange(0,10,0.1)
a = x + 1
b = np.sin(x)
c = 1.0/(1.0+x**2)

ax[0].plot( x, a )
ax[1].plot( x, b )
ax[2].plot( x, c )

for i in [0,1,2]:
    ax[i].set_xlim( [-0.2, 10.2] )

ax[2].set_xlabel( "x axis label" )
ax[2].get_xaxis().set_visible(True)
ax[3].get_xaxis().set_visible(False)

plt.show()
TheBigH
  • 524
  • 3
  • 15

3 Answers3

1

The problem is that the xlabel is created, but the bottom subplot is created on top of it, hiding it.

Assuming you want to keep your subplot layout exactly as it is, and just show the x axis label on top of the bottom subplot, you can change the zorder of the 3rd subplot (ax[2]), so that it is displayed above the other subplots. For example, add this just before plt.show():

ax[2].set_zorder(100)

and then you can see the xlabel and xticklabels

enter image description here

Otherwise, you will need to create some space between the axes, as @jeanrjc showed in their answer

tmdavison
  • 64,360
  • 12
  • 187
  • 165
0

The problem is the

fig.subplots_adjust( hspace=0.0)

line. Without it you get the labels.

Lageos
  • 183
  • 1
  • 9
  • For my purposes, I cannot add hspace and still have the plots large enough to be useful. I've tried. – TheBigH Mar 01 '16 at 13:15
  • 1
    OK, in this case use stackoverflow gridspec example [http://stackoverflow.com/a/28841567/4187194] (or see Matplotlib documentation [http://matplotlib.org/users/gridspec.html]). – Lageos Mar 01 '16 at 13:23
0

It actually works.

It is because you have this:

fig.subplots_adjust( hspace=0.0)

It sets the height spacing between plots, and with that you let no room for the labels. So, remove it

If you don't want to remove it, because what you may actually want is to move the last axes downward, then it's possible, just add this before plt.show():

bbox = ax[3].get_position()
ax[3].set_position([bbox.x0, bbox.y0-.075, bbox.width, bbox.height])
jrjc
  • 21,103
  • 9
  • 64
  • 78