ずれたラベル位置をマニュアル調整

pythonのmatplotlibライブラリで複数の図を並べて描くときに、軸のラベルが隣りの図に被ってしまうことがある。その解決方法。
例えば、何もユーザが指定しなければ、ラベルの位置は自動調整されて適当な場所に決められる。こんな風に...。

この図を描くpythonのコードは以下の通り。これは何の問題も無い。

import numpy as np
import matplotlib.pyplot as plt

def f(t):
    return np.exp(-t)*np.cos(2*np.pi*t)+1

t1 = np.arange(0.0, 5.0, 0.1)
t2 = np.arange(0.0, 5.0, 0.02)

fig = plt.figure()

plot1 = fig.add_subplot(221)
plot1.plot(t1, f(t1), 'bo', t2, f(t2), 'k')
plot1.set_xlabel('Time [sec]')
plot1.set_ylabel('some values are plotted [-]')

plot2 = fig.add_subplot(222)
plot2.plot(t2, np.cos(2*np.pi*t2)+2, 'r--')
plot2.set_xlabel('Time [sec]')
plot2.set_ylabel('some values are plotted [-]')
#plot2.set_yscale('log')

plt.show()

ところが、図のy軸をログスケールにしてみると、y軸のラベル位置が軸の数値に重ならないように自動調整された結果、見苦しい図になってしまう。上のコードのコメント行(set_yscale('log'))を有効にするとどんな図になるかというと、

この通り。右図に注目。ログスケールの場合、指数で表示される数値が幅を取るのでラベル位置がずらされて、隣りの図に被ってしまっている。これを修正するためには、ラベル位置を明示的にユーザが指定するしかない。具体的にどうやるかというと、

yaxis.set_label_coords(x座標, y座標)

を使えばいい。どこが原点になるのかちょっとわからなかったが、適当にx座標とy座標の値を調整したのが下図。

このときのソースは以下の通り。

import numpy as np
import matplotlib.pyplot as plt

def f(t):
    return np.exp(-t)*np.cos(2*np.pi*t)+1

t1 = np.arange(0.0, 5.0, 0.1)
t2 = np.arange(0.0, 5.0, 0.02)

fig = plt.figure()

plot1 = fig.add_subplot(221)
plot1.plot(t1, f(t1), 'bo', t2, f(t2), 'k')
plot1.set_xlabel('Time [sec]')
plot1.set_ylabel('some values are plotted [-]')

plot2 = fig.add_subplot(222)
plot2.plot(t2, np.cos(2*np.pi*t2)+2, 'r--')
plot2.set_xlabel('Time [sec]')
plot2.set_ylabel('some values are plotted [-]')
plot2.set_yscale('log')
plot2.yaxis.set_label_coords(-0.1, 0.5)

plt.show()

と、ここまでを必死で調べた。
[参考]The Matplotlib FAQ (release 0.99), 21.1.6 Align my ylabels across multiple subplots

(追記)
コメントをいただいた方法でやってみる。図の大きさも調整されて、2つの図がきれいに並ぶ。

#(略)...
plot2 = fig.add_subplot(222)
plot2.plot(t2, np.cos(2*np.pi*t2)+2, 'r--')
plot2.set_xlabel('Time [sec]')
plot2.set_ylabel('some values are plotted [-]')
plot2.set_yscale('log')
#plot2.yaxis.set_label_coords(-0.1, 0.5)
fig.subplots_adjust(left=0.2, wspace=0.4)

plt.show()