本文介绍了确定在 matplotlib 中单击按钮的子图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给出具有多个图的图形,是否可以确定使用鼠标按钮单击了哪个图?
Given a figure with multiple plots, is there a way to determine which of them was clicked with a mouse button?
例如
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
推荐答案
如果你保留了两个坐标轴的句柄,你可以只查询发生点击的坐标轴;例如 if event.inaxes == ax:
If you retain a handle to both axes, you may just query the axes in which the click has happened; e.g. 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()
这篇关于确定在 matplotlib 中单击按钮的子图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!