matplotlib交互式數據光標實現(xiàn)(mplcursors)
簡介
mplcursors
包也可以為matplotlib
提供交互式的數據光標(彈出式注釋框),它的靈感來源于mpldatacursor
包,可以認為是基于mpldatacursor
包的二次開發(fā)。
相對于mpldatacursor
包,mplcursors
包最大的特點就是提供了一些相對底層的API,這樣功能實現(xiàn)更加靈活。
安裝
pip install mplcursors
基本應用
mplcursors
包的基本應用方法與mpldatacursor
包類似,直接應用cursor
函數即可。
基本操作方法
- 鼠標左鍵單擊圖表數據元素時會彈出文本框顯示最近的數據元素的坐標值。
- 鼠標右鍵單擊文本框取消顯示數據光標。
- 按d鍵時切換顯示\關閉數據光標。
案例源碼
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()
mplcursors自定義應用
mpldatacursor
包中自定義功能主要通過向datacursor
函數傳遞實參實現(xiàn)。
mplcursors
包中的cursor
函數對標mpldatacursor
包中的datacursor
函數,但是在參數上發(fā)生了變化,保留了artists
、hover
、bindings
、multiple
、highlight
等類似參數。
mplcursors
包增加Selection
對象(底層為namedtuple
)表示選擇的數據元素的屬性。
當選中某個數據點時,可以通過添加(add
)或刪除(remove
)事件觸發(fā)、注冊回調函數實現(xiàn)功能,回調函數只有一個參數,及選擇的數據點。
在注冊回調函數時,mplcursors
包支持使用裝飾器。
mpldatacursor與mplcursors API對比
下面以修改顯示文本信息為例對比下mpldatacursor
與mplcursors
的不同實現(xiàn)方式。
mpldatacursor實現(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
實現(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
實現(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
包實現(xiàn)的功能與mpldatacursor
包非常相似。相對而言mplcursors
包的API更加靈活,通過connect
函數或者裝飾器自定義屬性耦合性更弱,便于實現(xiàn)繪圖與數據光標實現(xiàn)的分離。
參考
https://mplcursors.readthedocs.io/en/stable/
https://github.com/anntzer/mplcursors
到此這篇關于matplotlib交互式數據光標實現(xiàn)(mplcursors)的文章就介紹到這了,更多相關matplotlib交互式光標內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Django通過dwebsocket實現(xiàn)websocket的例子
今天小編就為大家分享一篇Django通過dwebsocket實現(xiàn)websocket的例子,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-11-11詳解使用python繪制混淆矩陣(confusion_matrix)
這篇文章主要介紹了詳解使用python繪制混淆矩陣(confusion_matrix),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-07-07Tensorflow中k.gradients()和tf.stop_gradient()用法說明
這篇文章主要介紹了Tensorflow中k.gradients()和tf.stop_gradient()用法說明,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-06-06