twinx

twinxは,パネルの左右に別々のy軸を示すために使う.twinxは既存のaxesに対して,x軸を共通にしたaxesを生成する.生成したaxesは,y軸がパネルの右に表示され,元のaxesと別のy軸を設定することができる.以下のスクリプトで,下のtwinx.pngのように,左右に別々の軸と軸ラベルがある図を作る.3つの以上の軸を持たせるには,後半の例にあるように spineの位置を調整する.プロットされた線と軸の関係を明確にするには,3軸の例に示したように,個別に線の色を指定し,legendまたは3軸の例で示すようにylabelのテキストの色と一致させるのがお勧めだ.from matplotlib import pyplot as pltimport numpy as npxs=np.arange(10)y1s=xsy2s=-xsy3s=np.random.randn(len(xs))*100plt.ion()plt.clf()plt.figure(1,(10.6))# ----- figure panel with two y-axes ---------ax_l=plt.subplot(2,1,1) # axes used for left axisax_r=ax_l.twinx() # axes used for right axisax_l.plot(xs,y1s)ax_r.plot(xs,y2s)ax_l.set_ylabel('ylabel 1')ax_r.set_ylabel('ylabel 2')plt.title('two axes figure')## ----- figure panel with three y-axes ---------ax_l=plt.subplot(2,1,2) # axes used for left axisax_r1=ax_l.twinx() # axes used for right axis-1ax_r2=ax_l.twinx() # axes used for right axis-2# adjust position of the second right axis rspine = ax_r2.spines['right'] rspine.set_position(('axes', 1.15))ax_l.plot(xs,y1s,'b')ax_r1.plot(xs,y2s,'r')ax_r2.plot(xs,y3s,'g')ax_l.set_ylabel('ylabel 1',color='b')ax_r1.set_ylabel('ylabel 2',color='r')ax_r2.set_ylabel('ylabel 3',color='b')plt.title('three axes figure')plt.subplots_adjust(right=0.75,bottom=0.1,top=0.9,hspace=0.4)plt.savefig('d:/temp/twinx.png')