如何在悬停在 python 的 matplotlib 图形中的给定列表中显示元素的索引号?
How can I show element's index number from a given list on hover in matplotlib graph in python?
我正在使用 mplcursors
模块来显示标签值。我还想显示给定列表中我将悬停的特定点的索引号。
我的示例代码片段:
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
来注释所需的信息(很简单)?
谢谢:)
mplcursors
允许指定每次在显示注释之前调用的函数。该函数获取一个参数 sel
,其中有一个 target
字段。在“线”的情况下,除了 xy 值外,目标还包含一个 index
。 index
的整数部分是光标所在段左端的 x
和 y
数组的索引。 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()
我正在使用 mplcursors
模块来显示标签值。我还想显示给定列表中我将悬停的特定点的索引号。
我的示例代码片段:
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
来注释所需的信息(很简单)?
谢谢:)
mplcursors
允许指定每次在显示注释之前调用的函数。该函数获取一个参数 sel
,其中有一个 target
字段。在“线”的情况下,除了 xy 值外,目标还包含一个 index
。 index
的整数部分是光标所在段左端的 x
和 y
数组的索引。 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()