from IPython.core.display import Image # グラフを残すためのおまじない
def save_and_display(filename):#おまじないの続き
import matplotlib.pyplot as plt
plt.savefig(filename,dpi=50)
return Image(filename=filename)
from matplotlib.gridspec import GridSpec
これはちょっと凝ったやり方ですが、使いたいときが出てくると思いますので、軽く紹介します。
gs = GridSpec(2, 5)
グリッド状のプロット領域をまずは用意します。2行5列です。
ax_full = plt.subplot(gs[0, :])
plt.title('Long Plot Space.')
ax=[]
for i in range(5):
ax.append(plt.subplot(gs[1,i]))
plt.title('space_'+str(i))
plt.tight_layout()
img=save_and_display('test.png')
img
0行目を繋げて一つの領域とし、1行目に一つずつ領域を設定しました。 こんな感じで割りと簡単にいろんな形の領域を設定することができます。 それぞれの領域にグラフを書くには次のようにします。
time=np.arange(128)
v=np.cos(np.pi*2.0*time/64.0)
ax_full.plot(time,v)
for i, _ax in enumerate(ax):
_ax.plot(v[0:64],v[i*4:i*4+64])
plt.draw()
img=save_and_display('test.png')
img
ここまでは、pylab=inlineでも使える手法です。
グラフのデータを変更することが可能です。 線の数を増やさずにデータの変化を確認する事は、全体像を把握するのに役立ちます。
def change_data(_ax, newx,newy):
lines=_ax.lines
line=lines[0]
line.set_xdata(newx)
line.set_ydata(newy)
_ax.relim()
_ax.autoscale_view()
newtime=time+50.0
newv=np.cos(np.pi*2.0*time/64.0)+np.cos(np.pi*2.0*time/32.0)+1.0
change_data(ax_full,newtime,newv)
for i, _ax in enumerate(ax):
change_data(_ax,newv[0:64],newv[i*4:i*4+64])
plt.draw()
img=save_and_display('test.png')
img
データを連続的に変えてみましょう。少し複雑になってきたので、クラスを定義します。
class MultiPlot(object):
from matplotlib.gridspec import GridSpec
def __init__(self):
self.gs = GridSpec(2, 5)
self.time=np.arange(128)
self.v=np.cos(np.pi*2.0*self.time/64.0)
self.f=plt.figure()
self.f.canvas.mpl_connect('button_press_event', self.replot)
self.ax_full = self.f.add_subplot(self.gs[0, :])
plt.title('Long Plot Space\n click your mouse.')
self.ax=[]
for i in range(5):
self.ax.append(self.f.add_subplot(self.gs[1,i]))
plt.title('space_'+str(i))
self.plot()
#axes=self.f.get_axes()
#self.ax_full=axes[0]
#self.ax=[]
#for i in range(5):
#self.ax.append(axes[i+1])
def replot(self,event):
self.time=self.time#+5.0
self.v=self.v+0.3*np.cos(np.pi*2.0*self.time/32.0)+0.5*np.cos(np.pi*2.0*self.time/16.0)
change_data(self.ax_full,self.time,self.v)
for i, _ax in enumerate(self.ax):
change_data(_ax,self.v[0:64],self.v[i*4:i*4+64])
plt.draw()
def plot(self):
self.ax_full.plot(self.time,self.v)
for i, _ax in enumerate(self.ax):
_ax.plot(self.v[0:64],self.v[i*4:i*4+64])
plt.draw()
これまでのグラフは閉じて、以下の行を実行してください。
mp=MultiPlot()
plt.tight_layout()
plt.tight_layout() は比較的新しい命令のようです。 これは今回のように沢山のグラフを表示する際の間隔を自動調整するようです。 名前が変な気がしますが。。
pylab=qtの場合には、Windowをリサイズした際にも、適宜主導で上記のセルを実行すれば空白が調整されます。
img=save_and_display('test.png')
img
マウスを何回かクリックすると、上のような図形が現れます。
今回はどういう応用があるでしょうか? 例えば、大量のスペクトルの吸収帯の部分がどうなっているか、ざっと眺めたい。 プレビューしたい。 という場合に使えると思います。