簡體   English   中英

確定matplotlib中單擊按鈕的按鈕

[英]Determine button clicked subplot in matplotlib

給定一個有多個圖的圖形,有沒有辦法確定用鼠標按鈕點擊了哪一個?

例如

fig = plt.figure()

ax  = fig.add_subplot(121)
ax.imshow(imsp0)

ax = fig.add_subplot(122)
ax.imshow(imsp1)

fig.canvas.mpl_connect("button_press_event",onclick_select)

def onclick_select(event):
  ... do something depending on the clicked subplot

至少可以通過應用以下步驟:

  • onclick事件具有屬性xy攜帶來自圖的角落的像素坐標

  • 可以使用fig.transFigure.inverted().transform((x,y))這些坐標轉換為圖形坐標fig.transFigure.inverted().transform((x,y))

  • 你可以通過bb=ax.get_position()得到每個子圖的邊界框

  • 迭代圖像的所有子圖(軸)

  • 您可以通過bb.contains(fx,fy)測試點擊是否在此邊界框的區域內,其中fxfy是按鈕點擊坐標轉換為圖像位置

有關onclick事件的更多信息: http//matplotlib.org/users/event_handling.html有關坐標轉換的更多信息,請訪問: http//matplotlib.org/users/transforms_tutorial.html

如果保留兩個軸的控制柄,則可以只查詢發生咔嗒聲的軸; 例如, if event.inaxes == ax:

import matplotlib.pyplot as plt
import numpy as np

imsp0 = np.random.rand(10,10)
imsp1 = np.random.rand(10,10)

fig = plt.figure()

ax  = fig.add_subplot(121)
ax.imshow(imsp0)

ax2 = fig.add_subplot(122)
ax2.imshow(imsp1)

def onclick_select(event):
    if event.inaxes == ax:
        print ("event in ax")
    elif event.inaxes == ax2:
        print ("event in ax2")

fig.canvas.mpl_connect("button_press_event",onclick_select)

plt.show()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM