pythonmatplotlibaxis

How to share x axes of two subplots after they have been created


I'm trying to share two subplots axes, but I need to share the x axis after the figure was created. E.g. I create this figure:

import numpy as np
import matplotlib.pyplot as plt

t = np.arange(1000)/100.
x = np.sin(2*np.pi*10*t)
y = np.cos(2*np.pi*10*t)

fig = plt.figure()
ax1 = plt.subplot(211)
plt.plot(t,x)
ax2 = plt.subplot(212)
plt.plot(t,y)

# some code to share both x axes

plt.show()

Instead of the comment I want to insert some code to share both x axes. How do I do this? There are some relevant sounding attributes _shared_x_axes and _shared_x_axes when I check to figure axis (fig.get_axes()) but I don't know how to link them.


Solution

  • The usual way to share axes is to create the shared properties at creation. Either

    fig=plt.figure()
    ax1 = plt.subplot(211)
    ax2 = plt.subplot(212, sharex = ax1)
    

    or

    fig, (ax1, ax2) = plt.subplots(nrows=2, sharex=True)
    

    Sharing the axes after they have been created should therefore not be necessary.

    However if for any reason, you need to share axes after they have been created (actually, using a different library which creates some subplots, like here might be a reason), there would still be a solution:

    Using

    ax2.sharex(ax1)
    

    creates a link between the two axes, ax1 and ax2. In contrast to the sharing at creation time, you will have to set the xticklabels off manually for one of the axes (in case that is wanted).

    A complete example:

    import numpy as np
    import matplotlib.pyplot as plt
    
    t= np.arange(1000)/100.
    x = np.sin(2*np.pi*10*t)
    y = np.cos(2*np.pi*10*t)
    
    fig=plt.figure()
    ax1 = plt.subplot(211)
    ax2 = plt.subplot(212)
    
    ax1.plot(t,x)
    ax2.plot(t,y)
    
    ax2.sharex(ax1)
    ax1.set_xticklabels([])
    # ax2.autoscale() ## call autoscale if needed
    
    plt.show()
    

    For a list of axes you would do:

    for ax in axes[1:]:
        ax.sharex(axes[0])