[英]Determine button clicked subplot in matplotlib
Given a figure with multiple plots, is there a way to determine which of them was clicked with a mouse button? 给定一个有多个图的图形,有没有办法确定用鼠标按钮点击了哪一个?
Eg 例如
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
It is possible at least by applying the following steps: 至少可以通过应用以下步骤:
the onclick event has attributes x
and y
carrying the pixel coordinates from the corner of the figure onclick事件具有属性x
和y
携带来自图的角落的像素坐标
these coordinates can be converted into figure coordinates by using fig.transFigure.inverted().transform((x,y))
可以使用fig.transFigure.inverted().transform((x,y))
这些坐标转换为图形坐标fig.transFigure.inverted().transform((x,y))
you can get the bounding box of each subplot by bb=ax.get_position()
你可以通过bb=ax.get_position()
得到每个子图的边界框
iterate through all subplots (axes) of the image 迭代图像的所有子图(轴)
you can test whether the click is within the area of this bounding box by bb.contains(fx,fy)
, where fx
and fy
are the button click coordinates transformed into image position 您可以通过bb.contains(fx,fy)
测试点击是否在此边界框的区域内,其中fx
和fy
是按钮点击坐标转换为图像位置
For more info on the onclick event: http://matplotlib.org/users/event_handling.html For more info on the coordinate transformations: http://matplotlib.org/users/transforms_tutorial.html 有关onclick事件的更多信息: http : //matplotlib.org/users/event_handling.html有关坐标转换的更多信息,请访问: http : //matplotlib.org/users/transforms_tutorial.html
If you retain a handle to both axes, you may just query the axes in which the click has happened; 如果保留两个轴的控制柄,则可以只查询发生咔嗒声的轴; eg if event.inaxes == ax:
例如, 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.