首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在python中的matplotlib图中显示给定列表中元素的索引号?

如何在python中的matplotlib图中显示给定列表中元素的索引号?
EN

Stack Overflow用户
提问于 2020-07-22 18:06:02
回答 1查看 561关注 0票数 0

我正在使用mplcursors模块来显示标签值。我还想显示给定列表中的索引号,用于我将悬停的特定点。我的示例代码片段:

代码语言:javascript
复制
import matplotlib.pyplot as plt
import mplcursors
lines = plt.plot([1, 2, 3, 4], [2, 4, 6, 10])
plt.ylabel('some numbers')
mplcursors.cursor(hover=True)
plt.show()

我是否可以使用mplcursors来注释所需的信息(因为它很简单)?谢谢:)

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-07-22 18:54:17

mplcursors允许指定每次在显示注释之前调用的函数。该函数获得一个参数sel,其中有一个target字段。在“行”的情况下,除了xy值之外,目标包含一个indexindex的整数部分是指向光标所在段左端的xy数组的索引。index的小数部分告诉我们在段的左端和右端之间有多远。

代码语言:javascript
复制
import matplotlib.pyplot as plt
import mplcursors

def show_annotation(sel):
    ind = int(sel.target.index)
    frac = sel.target.index - ind
    x, y = sel.target
    sel.annotation.set_text(f'left index:{ind} frac:{frac:.2f}\nx:{x:.2f} y:{y:.2f}')

lines = plt.plot([1, 2, 3, 4], [2, 4, 6, 10])
plt.ylabel('some numbers')
cursor = mplcursors.cursor(hover=True)
cursor.connect("add", show_annotation)
plt.show()

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63040566

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档