2017-10-31 11 views
1

私はMatplotlib NavigationToolbar2TkAggボタンを使ってサブプロットをナビゲートするために、同じデータをプロットするTkinterキャンバスに2つのmatplotlibサブプロットを持っています。トップパネルにデータの1つの領域を表示したいと思います(xlimits x1からx2 )、どちらのパネルでもユーザーがどのようにズーム/パンするかに基づいて、下のパネルにその領域からのオフセット(xlimits:x1 + offset〜x2 + offset)のデータが自動的に表示されます。私は基本的にTkinterのsharex/shareyの動作を探していますが、いくつかの単純な関数で制限値を操作しています。簡単な関数をトリガするNavigationToolbarイベントをキャッチする方法はありますか?私はこれについて間違ったやり方をしていますか?Tkinter内の他の制限に基づいてmatplotlibサブプロットの制限を自動的に更新しますか?

答えて

0

別のプロットの軸の限界に応じて、1つのプロットの新しい軸の制限を設定できます。両方の軸でxlim_changedイベントを使用して、現在の制限に応じて他のプロットの制限を調整する関数を呼び出します。
制限を変更する前にイベントを切断して、無限ループにならないようにする必要があります。

以下は、下のプロットが上のものと比較して100単位だけシフトされた実装です。

import numpy as np; np.random.seed(1) 
import matplotlib.pyplot as plt 

x = np.linspace(0,500,1001) 
y = np.convolve(np.ones(20), np.cumsum(np.random.randn(len(x))), mode="same") 

fig, (ax, ax2) = plt.subplots(nrows=2) 

ax.set_title("original axes") 
ax.plot(x,y) 
ax2.set_title("offset axes") 
ax2.plot(x,y) 

offset   = lambda x: x + 100 
inverse_offset = lambda x: x - 100 

class OffsetAxes(): 
    def __init__(self, ax, ax2, func, invfunc): 
     self.ax = ax 
     self.ax2 = ax2 
     self.func = func 
     self.invfunc = invfunc 
     self.cid = ax.callbacks.connect('xlim_changed', self.on_lims) 
     self.cid2 = ax2.callbacks.connect('xlim_changed', self.on_lims) 
     self.offsetaxes(ax, ax2, func) 

    def offsetaxes(self,axes_to_keep, axes_to_change, func): 
     self.ax.callbacks.disconnect(self.cid) 
     self.ax2.callbacks.disconnect(self.cid2) 
     xlim = np.array(axes_to_keep.get_xlim()) 
     axes_to_change.set_xlim(func(xlim)) 
     self.cid = ax.callbacks.connect('xlim_changed', self.on_lims) 
     self.cid2 = ax2.callbacks.connect('xlim_changed', self.on_lims) 

    def on_lims(self,axes): 
     print "xlim" 
     if axes == self.ax: 
      self.offsetaxes(self.ax, self.ax2, self.func) 
     if axes == self.ax2: 
      self.offsetaxes(self.ax2, self.ax, self.invfunc) 

o = OffsetAxes(ax, ax2, offset, inverse_offset) 


plt.show() 

enter image description here

関連する問題