[英]How do you automatically update matplotlib subplot limits based on another's limits within Tkinter?
我在Tkinter畫布中有兩個matplotlib子圖,它們繪制了相同的數據,並帶有Matplotlib NavigationToolbar2TkAgg按鈕供用戶瀏覽子圖,等等。我想讓頂部面板顯示數據的一個區域(x限制為x1到x2),而底部面板會根據用戶在任一面板中縮放/平移的方式自動顯示該區域的數據偏移量(xlimits:x1 + offset到x2 + offset)。 我本質上是在尋找Tkinter中的sharex / sharey行為,但是使用一些簡單的函數來控制極限值。 有沒有一種方法可以捕獲正在觸發一個簡單功能的NavigationToolbar事件; 還是我走錯路了?
您可以根據另一個圖的軸限制為一個圖設置新的軸限制。 在兩個軸上都使用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()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.