Reflect event handling on multiple subplots

六眼飞鱼酱① 提交于 2019-12-01 06:30:17

Annotating several images at once is not possible with the mpldatacursor package you use. But you may write your own "datacursor", which annotates the images.

This could then look as follows.

import matplotlib.pyplot as plt
import numpy as np

fig, ((ax1,ax2),(ax3,ax4)) = plt.subplots(nrows=2, 
                                          ncols=2,sharex=True, sharey=True)
plt.subplots_adjust(wspace=0.08, hspace=0.08)
ax1.imshow(np.random.random((10,10)))
ax2.imshow(np.random.random((10,10)))
ax3.imshow(np.random.random((10,10)))
ax4.imshow(np.random.random((10,10)))

class ImageCursor():
    def __init__(self, axes, fmt='x:{x}\ny:{y}\nz:{z:.3f}'):
        self.fmt = fmt
        self.axes = axes
        self.fig = self.axes[0].figure
        self.ims = []
        self.annot = []
        for ax in self.axes:
            ax.images[0].set_picker(True)
            self.ims.append(ax.images[0])
            annot = ax.annotate("",xy=(0,0), xytext=(-30,30),
                                textcoords="offset points",
                                arrowprops=dict(arrowstyle="->",color="w",
                                                connectionstyle="arc3"),
                                va="bottom", ha="left", fontsize=10,
                                bbox=dict(boxstyle="round", fc="w"),)
            annot.set_visible(False)
            self.annot.append(annot)
        self.cid = self.fig.canvas.mpl_connect("pick_event", self.pick)

    def pick(self,event):
        e = event.mouseevent
        if e.inaxes:
            x,y = int(np.round(e.xdata)), int(np.round(e.ydata))
            self.annotate((x,y))
    def annotate(self,X):
        for annot, im in zip(self.annot, self.ims):
            z = im.get_array()[X[0],X[1]]
            annot.set_visible(True)
            annot.set_text(self.fmt.format(x=X[0],y=X[1],z=z))
            annot.xy = X
        self.fig.canvas.draw_idle()

ic = ImageCursor([ax1,ax2,ax3,ax4])            

plt.show()

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!