主要问题是您正在创建一个新的canvas
而不是使用fig
已有的。有(至少)两种方法可以做你想做的事。
您可以通过将图像设置为响应选择事件来做到这一点(参见本教程示例 4):
cmap = mpl.colors.ListedColormap([[1,0,0], [0,0,1], [0,1,0], [1,1,0]])
xcolors = arange(15).reshape(15,1)
ycolors = arange(15).reshape(1,15)
fig = plt.figure(figsize=(6,6))
ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])
x_ax = fig.add_axes([0.05, 0.1, 0.05, 0.8])
x2_ax = fig.add_axes([0.05, 0.1, 0.05, 0.8])
y_ax = fig.add_axes([0.1, 0.05, 0.8, 0.05])
x_ax.imshow(xcolors, cmap=cmap, interpolation='none', picker=True)
x_ax.set_aspect('auto')
x_ax.set_position((0.1,0.1,0.05,0.8))
y_ax.imshow(ycolors, cmap=cmap, interpolation='none', picker=True)
def on_pick(event):
artist = event.artist
if isinstance(artist, matplotlib.image.AxesImage):
im = artist
A = im.get_array()
print A.shape,
print 'hello'
canvas = fig.canvas
canvas.mpl_connect('pick_event',on_pick)
或者,您可以设置轴以响应选择事件(请参阅颜色条 matplotlib python 上的 onclick 方法),如下所示:
cmap = mpl.colors.ListedColormap([[1,0,0], [0,0,1], [0,1,0], [1,1,0]])
xcolors = arange(15).reshape(15,1)
ycolors = arange(15).reshape(1,15)
fig = plt.figure(figsize=(6,6))
ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])
x_ax = fig.add_axes([0.05, 0.1, 0.05, 0.8])
x2_ax = fig.add_axes([0.05, 0.1, 0.05, 0.8])
y_ax = fig.add_axes([0.1, 0.05, 0.8, 0.05])
x_ax.imshow(xcolors, cmap=cmap, interpolation='none')
x_ax.set_aspect('auto')
x_ax.set_position((0.1,0.1,0.05,0.8))
y_ax.imshow(ycolors, cmap=cmap, interpolation='none')
x_ax.set_picker(5)
y_ax.set_picker(5)
def on_pick(event):
artist = event.artist
if isinstance(artist, matplotlib.axes.Axes):
print event.mouseevent.ydata,
print event.mouseevent.xdata,
print 'hello'
canvas = fig.canvas
canvas.mpl_connect('pick_event',on_pick)
请注意活动所携带的艺术家类型的差异(以及您可以轻松访问的信息)。