在matplotlib图像上悬停时显示工具提示

时间:2019-10-11 08:36:52

标签: python matplotlib

我正在使用matplotlib.image来可视化二维直方图,如以下MWE中所示:

import numpy as np

import matplotlib as mpl
import matplotlib.pyplot as plt

def hist(w, h, N):

    # Randomly pick N points on a w-by-h plane

    x = np.random.randint(w, size=N)
    y = np.random.randint(h, size=N)

    # Calculate the histogram

    xedges = np.arange(w+1)
    yedges = np.arange(h+1)

    count, _, _ = np.histogram2d(x, y, bins=(xedges, yedges))

    # Show the histogram as a 2D image

    xcenters = 0.5*(xedges[:-1] + xedges[1:])
    ycenters = 0.5*(yedges[:-1] + yedges[1:])

    count = count.T

    plt.figure()

    plt.gca().set_xlim(xedges[[0,-1]])
    plt.gca().set_ylim(yedges[[0,-1]])

    im = mpl.image.NonUniformImage(plt.gca())
    im.set_data(xcenters, ycenters, count)

    plt.gca().images.append(im)

if __name__ == "__main__":
    hist(64, 48,  10000)
    plt.show(block=True)

产生如下图像:

sample output of the MWE

将鼠标悬停在坐标count[i][j]上的像素作为工具提示时,能够看到(i, j)的值将很有帮助。有办法吗?

1 个答案:

答案 0 :(得分:0)

您可以绑定到'motion_notify_event'并通过注释显示信息:

import numpy as np

import matplotlib as mpl
import matplotlib.pyplot as plt

def hist(w, h, N):

    # Randomly pick N points on a w-by-h plane

    ...

    plt.gca().images.append(im)

    def hover(event):
        x, y = event.xdata, event.ydata
        try:
            pos = f"{x:.2f},{y:.2f}"
        except TypeError:
            return
        global txt
        if not txt:
            txt = plt.annotate(pos, xy=(x, y), color='red',
                               bbox=dict(boxstyle='round,pad=0.2', fc='yellow'))
        else:
            txt.set_x(x)
            txt.set_y(y)
            txt.set_text(pos)
        plt.draw()

    fig.canvas.mpl_connect('motion_notify_event', hover)

if __name__ == "__main__":
    hist(64, 48,  10000)
    txt = None
    plt.show(block=True)