Sometimes you may want to share axis scale across multiple axes. Let’s have a look at the following example:
%matplotlib inline
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-10, 10, 100)
y1 = x ** 2 - 2 * x + 3
y2 = 10 * np.sin(x)
y3 = 2 * x + 1
fig, axes = plt.subplots(3, 1)
# Here are the axes in three rows and one column.
axes[0].plot(x, y1, color='red')
axes[1].plot(x, y2, color='green')
axes[2].plot(x, y3, color='blue')
As you can see, the coordinates are not very readable. You can see right away that we’re using the same scale for the X axis, so we don’t have to repeat the tick labels for each axis individually. In order to share the scale on the X axis we set the sharex argument to True:
# Let's share the axis scale on the X axis.
fig, axes = plt.subplots(3, 1, sharex=True)
# Here are the axes in three rows and one column.
axes[0].plot(x, y1, color='red')
axes[1].plot(x, y2, color='green')
axes[2].plot(x, y3, color='blue')
Now it looks much more readable. And now let’s have a look at the other example where the axes are in one row and three columns:
fig, axes = plt.subplots(1, 3)
# Here are the axes in one row and three columns.
axes[0].plot(x, y1, color='red')
axes[1].plot(x, y2, color='green')
axes[2].plot(x, y3, color='blue')
This time the scales on the Y axis are not the same, but we can still share them. The plots will adjust themselves to the shared scale. This time we should set the sharey argument to True:
# Let's share the axis scale on the X axis.
fig, axes = plt.subplots(1, 3, sharey=True)
# Here are the axes in one row and three columns.
axes[0].plot(x, y1, color='red')
axes[1].plot(x, y2, color='green')
axes[2].plot(x, y3, color='blue')
Now the tick labels are more readable, although the plots themselves not necessarily so. It all depends on what you need. You may also share axis scale on both axes. Let’s have a look at this simple example with just some empty axes:
fig, axes = plt.subplots(4, 4)
And now suppose that we want all the axes to share both the X and Y axis scales. Here’s how we can do it:
fig, axes = plt.subplots(4, 4, sharex=True, sharey=True)
This is much more readable now.