Interactive subplots: make all x-axes move together

It’s very easy to make subplots that share an x-axis, so that when you pan and zoom on one axis, the others automatically pan and zoom as well. The key to this functionality is the sharex keyword argument, which is used when creating an axis. Here’s some example code and a video of the resulting interaction.


from pylab import figure, show

# Create some data: one x, three different y
x = arange(0.0, 20.0, 0.01)
y1 = sin(2*pi*x)
y2 = exp(-x)
y3 = y1*y2

# Create a figure and add three subplots.
fig = figure()
ax1 = fig.add_subplot(311)
ax2 = fig.add_subplot(312, sharex=ax1)  # share ax1's xaxis
ax3 = fig.add_subplot(313, sharex=ax1)  # share ax1's xaxis

# Plot
ax1.plot(x,y1)
ax2.plot(x,y2)
ax3.plot(x,y3)

# Show the figure.
show()

Here’s a video of what the interaction is like with this figure (matplotlib automatically adds the pan, zoom, home, etc buttons to all figures):

Notice that the y-axis remained independent in each of the three subplots. As you’d expect, the add_subplot() method accepts a sharey keyword argument as well. You can even pass both sharex and sharey . . . this is most useful when two subplots show data with the same units.

Tags: , ,

Leave a Reply