Two ways to align ylabels for two plots using Python and matplotlib.pyplot


The result is:

Two ways to align ylabels for two plots using Python and matplotlib.pyplot

This page shows two ways to align two ylabels for two subplots using Python and matplotlib.pyplot.

See also:

Python Matplotlib Tips: One ylabel for two subplots using Python Matplotlib.pyplot

Learn how to draw one ylabel for two vertical subplots using python matplotlib.pyplot


In [1]:
from platform import python_version as pythonversion
print('python: '+pythonversion())

import matplotlib.pyplot as plt
from matplotlib import __version__ as matplotlibversion
print('matplotlib: '+matplotlibversion)

import numpy as np
from numpy import __version__ as numpyversion
print('numpy: '+numpyversion)
%matplotlib inline
python: 3.6.3
matplotlib: 3.0.1
numpy: 1.15.4
In [2]:
x = np.arange(0,10,0.01)
y1 = np.abs(np.sin(x))
y2 = 100*np.sin(x)
In [3]:
plt.figure(figsize=(4.7,3.7),facecolor="w")
ax1 = plt.subplot(2,1,1)
ax2 = plt.subplot(2,1,2,sharex=ax1)
ax1.plot(x,y1)
ax2.plot(x,y2)
ax1.set_ylabel("y Axis 1")
ax2.set_ylabel("y Axis 2")
ax2.set_xlabel("x Axis")
plt.setp(ax1.get_xticklabels(),visible=False)
plt.savefig('another-way-to-align-two-ylabels-1.png', bbox_inches='tight', pad_inches=0.02)

One way to align two ylabels

In [4]:
plt.figure(figsize=(4.7,3.7),facecolor="w")
ax1 = plt.subplot(2,1,1)
ax2 = plt.subplot(2,1,2,sharex=ax1)
ax1.plot(x,y1)
ax2.plot(x,y2)
ax1.set_ylabel("y Axis 1")
ax2.set_ylabel("y Axis 2")
ax2.set_xlabel("x Axis")
ax1.yaxis.set_label_coords(-0.1,0.5)
ax2.yaxis.set_label_coords(-0.1,0.5)
plt.setp(ax1.get_xticklabels(),visible=False)
plt.savefig("./another-way-to-align-two-ylabels-2.png",dpi=250,bbox_inches="tight",pad_inches=0.02)

The another way to align two ylabels

In [5]:
fig = plt.figure(figsize=(4.7,3.7),facecolor="w")
ax1 = fig.add_subplot(2,1,1)
ax2 = fig.add_subplot(2,1,2,sharex=ax1)
ax1.plot(x,y1)
ax2.plot(x,y2)
ax1.set_ylabel("y Axis 1")
ax2.set_ylabel("y Axis 2")
ax2.set_xlabel("x Axis")
plt.setp(ax1.get_xticklabels(),visible=False)
fig.align_ylabels([ax1,ax2])
plt.savefig("another-way-to-align-two-ylabels-3.png",dpi=250,bbox_inches="tight",pad_inches=0.02)