簡體   English   中英

如何在 python 中的 matplotlib 圖中的 hover 上的給定列表中顯示元素的索引號?

[英]How can I show element's index number from a given list on hover in matplotlib graph in python?

我正在使用mplcursors模塊來顯示 label 值。 我還想顯示給定列表中我將 hover 的特定點的索引號。 我的示例代碼片段:

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允許指定一個 function ,每次在顯示注釋之前調用它。 function 得到一個參數sel ,其中包括一個target字段。 在“線”的情況下,除了 xy 值之外,目標還包含一個index index的 integer 部分是 cursor 所在段左端的xy arrays 的索引。 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM