栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

将鼠标悬停在matplotlib中的某个点上时可以显示标签吗?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

将鼠标悬停在matplotlib中的某个点上时可以显示标签吗?

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

import matplotlib.pyplot as pltimport 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.RdYlGnfig,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(box, fc="w"),         arrowprops=dict(arrow))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()

由于人们还希望将此解决方案用于行plot而不是分散,因此以下内容将是相同的解决方案plot(其工作原理略有不同)。

Hide pre snippetimport matplotlib.pyplot as pltimport 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.RdYlGnfig,ax = plt.subplots()line, = plt.plot(x,y, marker="o")annot = ax.annotate("", xy=(0,0), xytext=(-20,20),textcoords="offset points",         bbox=dict(box, fc="w"),         arrowprops=dict(arrow))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()


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/638604.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号