2017-07-12 7 views
4

matplotlibで複数のxlabelsを一度に割り当てたいと思います。 複数のxlabelsを次のように割り当てます。matplotlibで複数のxlabelsを一度に割り当てる方法はありますか?

import matplotlib.pyplot as plt 

fig1 = plt.figure() 
ax1 = fig1.add_subplot(211) 
ax1.set_xlabel("x label") 
ax2 = fig1.add_subplot(212) 
ax2.set_xlabel("x label") 

私はこのように冗長であると感じます。 複数のxlabelsを一度に割り当てる方法はありますか?

(ax1,ax2).set_xlabel("x label") 

答えて

3

リストの理解を使用することができます。

[ax.set_xlabel("x label") for ax in [ax1,ax2]] 

また、すでに、サブプロットの作成時にラベルを設定する1つのラインへの質問から完全なコードを単純化することがあります。

fig, (ax1, ax2) = plt.subplots(nrows=2, ncols=1, subplot_kw=dict(xlabel="xlabel")) 
+0

ありがとうございました! – user6695701

3

あなたはリストにあなたのaxオブジェクトを格納することができます。 subplots機能を使用することにより、このリストは自動的に作成されます。

import matplotlib.pyplot as plt 

fig, axes = plt.subplots(nrows=1, ncols=2) 

[ax.set_xlabel("x label") for ax in axes] 

axes[0,0].plot(data)  # whatever you want to plot 
0

それはあなたの意図が明確になりますように私は、通常のfor -loopを好む:

for ax in [ax1, ax2]: 
    ax.set_xlabel("x label") 

を使用すると、ワンライナーを希望する場合関数を覚えています:

map(lambda ax : ax.set_xlabel("x label"), [ax1, ax2]) 
関連する問題