[英]Update the x-axis of a matplotlib subplot according to the y-axis of a different subplot
我想繪制一個像這樣的正交投影:
使用matplotlib,可能包括3D子圖。 所有子圖應共享公共軸。
fig = plt.figure()
ax = fig.add_subplot(221, title="XZ")
bx = fig.add_subplot(222, title="YZ", sharey=ax)
cx = fig.add_subplot(223, title="XY", sharex=ax, sharey=[something like bx.Xaxis])
dx = fig.add_subplot(224, title="XYZ", projection="3d", sharex=ax, sharey=bx, sharez=[something like bx.Yaxis]
我無法弄清楚如何將一個圖的x軸與另一個圖的y軸“鏈接”。 有沒有辦法做到這一點?
晚會晚了,但是...
通過手動將一個子圖的軸數據與其他子圖的軸數據一起更新,您應該能夠完成所需的工作。
從您的文章使用的符號,例如,可以匹配ylim
值cx
與xlim
值bx
使用get
和set
方法。
cx.set_ylim(bx.get_ylim())
同樣,您可以在各個子圖之間匹配刻度標簽和位置。
bx_xticks = bx.get_xticks()
bx_xticklabels = [label.get_text() for label in bx.get_xticklabels()]
cx.set_yticks(bx_xticks)
cx.set_yticklabels(bx_xticklabels)
您應該能夠以這種方式從已實例化的子圖中動態定義所有軸屬性和對象。
我通過利用事件處理程序解決1的問題。 偵聽"*lim_changed"
事件,然后正確獲取get_*lim
和set*_lim
以同步限制就可以了。 注意,您還必須在右上方的圖YZ中反轉x軸。
這是將x軸與y軸同步的示例函數:
def sync_x_with_y(self, axis):
# check whether the axes orientation is not coherent
if (axis.get_ylim()[0] > axis.get_ylim()[1]) != (self.get_xlim()[0] > self.get_xlim()[1]):
self.set_xlim(axis.get_ylim()[::-1], emit=False)
else:
self.set_xlim(axis.get_ylim(), emit=False)
我實現了一個簡單的正交投影類,使繪制此類圖變得非常容易。
1從暗示本傑明·根(Benjamin Root)在大約一年前將我送入matplotlib郵件列表...對不起,您之前未發布解決方案
這是我解決這個問題的方法,基本上是@elebards答案的精簡版本。 我只是將更新限制方法添加到axes類,因此它們可以訪問set_xlim / set_ylim方法。 然后,將這些函數連接到要同步的軸的回調中。 當這些被調用時,事件參數將被填充
import types
import matplotlib.pyplot as plt
def sync_y_with_x(self, event):
self.set_xlim(event.get_ylim(), emit=False)
def sync_x_with_y(self, event):
self.set_ylim(event.get_xlim(), emit=False)
fig = plt.figure()
ax1 = fig.add_subplot(211)
ax2 = fig.add_subplot(212)
ax1.update_xlim = types.MethodType(sync_y_with_x, ax1)
ax2.update_ylim = types.MethodType(sync_x_with_y, ax2)
ax1.callbacks.connect("ylim_changed", ax2.update_ylim)
ax2.callbacks.connect("xlim_changed", ax1.update_xlim)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.