[英]How can I show element's index number from a given list on hover in matplotlib graph in python?
I am using mplcursors
module to show label value.我正在使用
mplcursors
模块来显示 label 值。 I also want to show the index number from given lists for that particular point on which I will hover.我还想显示给定列表中我将 hover 的特定点的索引号。 My Example Code snippet:
我的示例代码片段:
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()
Is there any way that I can use the mplcursors
to annotate the required information(as its easy)?有什么方法可以使用
mplcursors
来注释所需的信息(因为它很容易)? Thanks:)谢谢:)
mplcursors
allows to specify a function that is called every time just before an annotation is shown. mplcursors
允许指定一个 function ,每次在显示注释之前调用它。 That function gets a parameter sel
which among others has a target
field. function 得到一个参数
sel
,其中包括一个target
字段。 In case of a "line", apart from the xy value, the target contains an index
.在“线”的情况下,除了 xy 值之外,目标还包含一个
index
。 The integer part of the index
is an index into the x
and y
arrays of the left end of the segment the cursor is on. index
的 integer 部分是 cursor 所在段左端的x
和y
arrays 的索引。 The fractional part of the index
tells how far we are between the left and the right end of the segment. index
的小数部分告诉我们在段的左端和右端之间有多远。
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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.