您好,登錄后才能下訂單哦!
這篇文章給大家介紹怎么在matplotlib中實(shí)現(xiàn)一個(gè)交互式數(shù)據(jù)光標(biāo)效果,內(nèi)容非常詳細(xì),感興趣的小伙伴們可以參考借鑒,希望對(duì)大家能有所幫助。
mplcursors
包也可以為matplotlib
提供交互式的數(shù)據(jù)光標(biāo)(彈出式注釋框),它的靈感來源于mpldatacursor
包,可以認(rèn)為是基于mpldatacursor
包的二次開發(fā)。
相對(duì)于mpldatacursor
包,mplcursors
包最大的特點(diǎn)就是提供了一些相對(duì)底層的API,這樣功能實(shí)現(xiàn)更加靈活。
pip install mplcursors
mplcursors
包的基本應(yīng)用方法與mpldatacursor
包類似,直接應(yīng)用cursor
函數(shù)即可。
鼠標(biāo)左鍵單擊圖表數(shù)據(jù)元素時(shí)會(huì)彈出文本框顯示最近的數(shù)據(jù)元素的坐標(biāo)值。
鼠標(biāo)右鍵單擊文本框取消顯示數(shù)據(jù)光標(biāo)。
按d鍵時(shí)切換顯示\關(guān)閉數(shù)據(jù)光標(biāo)。
import matplotlib.pyplot as plt import numpy as np import mplcursors data = np.outer(range(10), range(1, 5)) fig, ax = plt.subplots() lines = ax.plot(data) ax.set_title("Click somewhere on a line.\nRight-click to deselect.\n" "Annotations can be dragged.") mplcursors.cursor(lines) # or just mplcursors.cursor() plt.show()
mpldatacursor
包中自定義功能主要通過向datacursor
函數(shù)傳遞實(shí)參實(shí)現(xiàn)。mplcursors
包中的cursor
函數(shù)對(duì)標(biāo)mpldatacursor
包中的datacursor
函數(shù),但是在參數(shù)上發(fā)生了變化,保留了artists
、hover
、bindings
、multiple
、highlight
等類似參數(shù)。mplcursors
包增加Selection
對(duì)象(底層為namedtuple
)表示選擇的數(shù)據(jù)元素的屬性。
當(dāng)選中某個(gè)數(shù)據(jù)點(diǎn)時(shí),可以通過添加(add
)或刪除(remove
)事件觸發(fā)、注冊(cè)回調(diào)函數(shù)實(shí)現(xiàn)功能,回調(diào)函數(shù)只有一個(gè)參數(shù),及選擇的數(shù)據(jù)點(diǎn)。
在注冊(cè)回調(diào)函數(shù)時(shí),mplcursors
包支持使用裝飾器。
下面以修改顯示文本信息為例對(duì)比下mpldatacursor
與mplcursors
的不同實(shí)現(xiàn)方式。
import matplotlib.pyplot as plt import numpy as np from mpldatacursor import datacursor ax=plt.gca() labels = ["a", "b", "c"] for i in range(3): ax.plot(i, i,'o', label=labels[i]) datacursor(formatter='{label}'.format) plt.show()
mplcursors
實(shí)現(xiàn)方式一
import matplotlib.pyplot as plt import numpy as np import mplcursors ax=plt.gca() lines = ax.plot(range(3), range(3), "o") labels = ["a", "b", "c"] cursor = mplcursors.cursor(lines) cursor.connect( "add", lambda sel: sel.annotation.set_text(labels[sel.target.index])) plt.show()
mplcursors
實(shí)現(xiàn)方式二
import matplotlib.pyplot as plt import numpy as np import mplcursors ax=plt.gca() lines = ax.plot(range(3), range(3), "o") labels = ["a", "b", "c"] cursor = mplcursors.cursor(lines) @cursor.connect("add") def on_add(sel): sel.annotation.set_text(labels[sel.target.index]) plt.show()
mplcursors
包實(shí)現(xiàn)的功能與mpldatacursor
包非常相似。相對(duì)而言mplcursors
包的API更加靈活,通過connect
函數(shù)或者裝飾器自定義屬性耦合性更弱,便于實(shí)現(xiàn)繪圖與數(shù)據(jù)光標(biāo)實(shí)現(xiàn)的分離。
關(guān)于怎么在matplotlib中實(shí)現(xiàn)一個(gè)交互式數(shù)據(jù)光標(biāo)效果就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,可以學(xué)到更多知識(shí)。如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。