matplotlib のサンプルコードを実行している際にタイトルのようなエラーに遭遇。
実証コードは↓
import matplotlib.pyplot as plt
import numpy as np
np.random.seed(20171217)
fig = plt.figure()
for i in range(1,8):
subplot = fig.add_subplot(4, 4, i)
subplot.set_xticks([])
subplot.set_yticks([])
subplot.imshow(np.random.random((100, 100)), cmap=plt.cm.gray_r, interpolation='nearest')
for i in range(1,8):
subplot = fig.add_subplot(4, 4, i+1)
subplot.set_xticks([])
subplot.set_yticks([])
subplot.imshow(np.random.random((100, 100)), cmap=plt.cm.BuPu_r, interpolation='nearest')
Warning 全文は↓
/usr/local/share/anaconda3/lib/python3.6/site-packages/matplotlib/cbook/deprecation.py:106: MatplotlibDeprecationWarning: Adding an axes using the same arguments as a previous axes currently reuses the earlier instance. In a future version, a new instance will always be created and returned. Meanwhile, this warning can be suppressed, and the future behavior ensured, by passing a unique label to each axes instance.
warnings.warn(message, mplDeprecation, stacklevel=1)
問題点は add_axes() 関数を使っていないのにどこでエラーになるか、ということ。
なお、add_axes() 関数のリファレンスは以下を参照
add_axes(*args, **kwargs)
サンプルコードで検証したところ、add_subplot() 関数で同じパラメータを渡すとこのエラーが出るらしいと判明。add_subplot() 関数のリファレンスは以下を参照。
add_subplot(*args, **kwargs)
上記の拙いコードでは、2 回目の subplot(4, 4, i+1) とやっている箇所で 1 回目の subplot(4, 4, i) の呼び出しと同じ引数を呼び出しているから生じるらしい。
正しく動作する ( Warning が出ない ) バージョンは↓
import matplotlib.pyplot as plt
import numpy as np
np.random.seed(20171217)
fig = plt.figure()
counter = 0
for i in range(1,8):
subplot = fig.add_subplot(4, 4, i)
subplot.set_xticks([])
subplot.set_yticks([])
subplot.imshow(np.random.random((100, 100)), cmap=plt.cm.gray_r, interpolation='nearest')
for i in range(1,8):
subplot = fig.add_subplot(4, 4, i+8)
subplot.set_xticks([])
subplot.set_yticks([])
subplot.imshow(np.random.random((100, 100)), cmap=plt.cm.BuPu_r, interpolation='nearest')
ただ単に 2 回目の for ループの add_subplot() 関数の 3 番目の引数を i+1 から i+8 に変更しただけ。
〇 対策
「ソースコード写し間違っていませんか」という話になると思います。
色々調べましたが、add_subplot() 関数には、stacklebel といったターゲット引数は指定できません。
〇 実行環境
・jupyter
・jupyterhub
・anaconda
・