I am using matplotlib to make scatter plots. Each point on the scatter plot is associated with a named object. I would like to be able to see the name of an object when I hover my cursor over the point on the scatter plot associated with that object. In particular, it would be nice to be able to quickly see the names of the points that are outliers. The closest thing I have been able to find while searching here is the annotate command, but that appears to create a fixed label on the plot. Unfortunately, with the number of points that I have, the scatter plot would be unreadable if I labeled each point. Does anyone know of a way to create labels that only appear when the cursor hovers in the vicinity of that point?

我使用matplotlib制作散点图。散点图上的每个点都与命名对象相关联。当我将光标悬停在与该对象关联的散点图上的点上时,我希望能够看到对象的名称。特别是,能够快速查看异常点的名称会很高兴。我在这里搜索时能够找到的最接近的东西是annotate命令,但这似乎在图上创建了一个固定的标签。不幸的是,根据我拥有的点数,如果我标记了每个点,散点图将是不可读的。有没有人知道一种创建标签的方法,只有当光标悬停在该点附近时才会出现?

6 个解决方案

#1


24

It seems none of the other answers here actually answer the question. So here is a code that uses a scatter and shows an annotation upon hovering over the scatter points.

似乎这里没有其他答案实际上回答了这个问题。因此,这是一个使用散点图的代码,并在将鼠标悬停在散点图上时显示注释。

import matplotlib.pyplot as plt
import numpy as np; np.random.seed(1)

x = np.random.rand(15)
y = np.random.rand(15)
names = np.array(list("ABCDEFGHIJKLMNO"))
c = np.random.randint(1,5,size=15)

norm = plt.Normalize(1,4)
cmap = plt.cm.RdYlGn

fig,ax = plt.subplots()
sc = plt.scatter(x,y,c=c, s=100, cmap=cmap, norm=norm)

annot = ax.annotate("", xy=(0,0), xytext=(20,20),textcoords="offset points",
                    bbox=dict(boxstyle="round", fc="w"),
                    arrowprops=dict(arrowstyle="->"))
annot.set_visible(False)

def update_annot(ind):

    pos = sc.get_offsets()[ind["ind"][0]]
    annot.xy = pos
    text = "{}, {}".format(" ".join(list(map(str,ind["ind"]))), 
                           " ".join([names[n] for n in ind["ind"]]))
    annot.set_text(text)
    annot.get_bbox_patch().set_facecolor(cmap(norm(c[ind["ind"][0]])))
    annot.get_bbox_patch().set_alpha(0.4)


def hover(event):
    vis = annot.get_visible()
    if event.inaxes == ax:
        cont, ind = sc.contains(event)
        if cont:
            update_annot(ind)
            annot.set_visible(True)
            fig.canvas.draw_idle()
        else:
            if vis:
                annot.set_visible(False)
                fig.canvas.draw_idle()

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

plt.show()

Because people suddenly also want to use this solution for a line plot instead of a scatter, the following would be the same solution for plot (which works slightly differently).

因为人们突然也想要将此解决方案用于线图而不是散点图,所以以下对于绘图(其工作方式略有不同)将是相同的解决方案。

import matplotlib.pyplot as plt
import numpy as np; np.random.seed(1)

x = np.sort(np.random.rand(15))
y = np.sort(np.random.rand(15))
names = np.array(list("ABCDEFGHIJKLMNO"))

norm = plt.Normalize(1,4)
cmap = plt.cm.RdYlGn

fig,ax = plt.subplots()
line, = plt.plot(x,y, marker="o")

annot = ax.annotate("", xy=(0,0), xytext=(-20,20),textcoords="offset points",
                    bbox=dict(boxstyle="round", fc="w"),
                    arrowprops=dict(arrowstyle="->"))
annot.set_visible(False)

def update_annot(ind):
    x,y = line.get_data()
    annot.xy = (x[ind["ind"][0]], y[ind["ind"][0]])
    text = "{}, {}".format(" ".join(list(map(str,ind["ind"]))), 
                           " ".join([names[n] for n in ind["ind"]]))
    annot.set_text(text)
    annot.get_bbox_patch().set_alpha(0.4)


def hover(event):
    vis = annot.get_visible()
    if event.inaxes == ax:
        cont, ind = line.contains(event)
        if cont:
            update_annot(ind)
            annot.set_visible(True)
            fig.canvas.draw_idle()
        else:
            if vis:
                annot.set_visible(False)
                fig.canvas.draw_idle()

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

plt.show()

更多相关文章

  1. Python(名称空间、函数嵌套、函数对象)
  2. flask-admin 新增功能关联两张表,关联的表中的字段显示出来是对象
  3. 小白学Python---面向对象02
  4. AttributeError:“MatrixFactorizationModel”对象没有属性“sav
  5. Python:在类中定义对象
  6. 自动完成在VS代码和Python中的自动化对象
  7. 具有相同时区但不同的utcoffset()的Datetime对象
  8. Python 【面向对象(类)】 学习笔记
  9. 如何将json转换为对象?

随机推荐

  1. Android 支持不同(本地化、屏幕、版本)设备
  2. android的Instrumentation详解
  3. unity与android的无缝连接
  4. Android:Task概念以及相关
  5. 尚硅谷15天Android基础笔记
  6. Android 实现ListView 3D效果 - 2 - 弹性
  7. Android(安卓)数据库SQLiteDatabase的使
  8. Google Android真实的谎言
  9. [Android] Android进程与线程基本知识
  10. Android布局优化(五)绘制优化—避免过度绘