那么在Python中,特別是使用最常用的matplotlib庫繪制的圖像能否實(shí)現(xiàn)上述功能呢?這里為大家介紹一個(gè)可以實(shí)現(xiàn)交互式創(chuàng)建標(biāo)簽的第三方庫:"mplcursors"
基本介紹
mplcursors 為 Matplotlib 提供交互式數(shù)據(jù)選擇游標(biāo)。它的靈感來自 mpldatacursor,具有大大簡化的 API。
由于缺乏維護(hù),這里不建議大家使用"mpldatacursor"。
mpldatacursor的更新記錄
mplcursors的更新記錄
安裝方式為:
$ pip install mplcursors # from PyPI
$ pip install git+https://github.com/anntzer/mplcursors # from Github
在使用過程中的操作為:
示例
這里使用matplotlib和mplcursors繪制與文首Matlab繪圖相同的圖像,需要用到下述代碼:
import matplotlib.pyplot as plt
import numpy as np
import mplcursors #調(diào)用mplcursor
data = np.outer(range(10), range(1, 5))
fig, ax = plt.subplots()
ax.set_title("Multiple non-draggable annotations")
ax.plot(data)
mplcursors.cursor(multiple=True) #設(shè)置多個(gè)游標(biāo)
plt.show()
多游標(biāo)功能:
可以使用鼠標(biāo)對(duì)游標(biāo)進(jìn)行拖動(dòng):
可以單獨(dú)為每一個(gè)數(shù)據(jù)點(diǎn)定制游標(biāo):
import matplotlib.pyplot as plt
import mplcursors
import numpy as np
labels = ["a", "b", "c", "d", "e"]
x = np.array([0, 1, 2, 3, 4])
fig, ax = plt.subplots()
line, = ax.plot(x, x, "ro")
mplcursors.cursor(ax).connect(
"add", lambda sel: sel.annotation.set_text(labels[sel.index]))
plt.show()
柱狀圖也可以添加游標(biāo):
import string
import matplotlib.pyplot as plt
import mplcursors
fig, ax = plt.subplots()
ax.bar(range(9), range(1, 10), align="center")
labels = string.ascii_uppercase[:9]
ax.set(xticks=range(9), xticklabels=labels, title="Hover over a bar")
# With HoverMode.Transient, the annotation is removed as soon as the mouse
# leaves the artist. Alternatively, one can use HoverMode.Persistent (or True)
# which keeps the annotation until another artist gets selected.
cursor = mplcursors.cursor(hover=mplcursors.HoverMode.Transient)
@cursor.connect("add")
def on_add(sel):
x, y, width, height = sel.artist[sel.index].get_bbox().bounds
sel.annotation.set(text=f"{x+width/2}: {height}",
position=(0, 20), anncoords="offset points")
sel.annotation.xy = (x + width / 2, y + height)
plt.show()
聯(lián)系客服