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

Solution 1:

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

ax1.get_shared_x_axes().join(ax1, ax2)

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)

ax1.get_shared_x_axes().join(ax1, ax2)
ax1.set_xticklabels([])
# ax2.autoscale() ## call autoscale if needed

plt.show()

Solution 2:

As of Matplotlib v3.3 there now exist Axes.sharex, Axes.sharey methods:

ax1.sharex(ax2)
ax1.sharey(ax3)

Solution 3:

Just to add to ImportanceOfBeingErnest's answer above:

If you have an entire list of axes objects, you can pass them all at once and have their axes shared by unpacking the list like so:

ax_list = [ax1, ax2, ... axn] #< your axes objects 
ax_list[0].get_shared_x_axes().join(*ax_list)

The above will link all of them together. Of course, you can get creative and sub-set your list to link only some of them.

Note:

In order to have all axes linked together, you do have to include the first element of the axes_list in the call, despite the fact that you are invoking .get_shared_x_axes() on the first element to start with!

So doing this, which would certainly appear logical:

ax_list[0].get_shared_x_axes().join(*ax_list[1:])

... will result in linking all axes objects together except the first one, which will remain entirely independent from the others.