在使用Matplotlib畫圖過程中,有些內容必須鼠標點擊或者劃過才可以顯示,這個問題可以依賴于
annotate(s='str' ,xy=(x,y) ,xytext=(l1,l2) ,..)
這個函數,其中s 為注釋文本內容 , xy 為被注釋的坐標點, xytext 為注釋文字的坐標位置,其他參數可自行百度哈。當鼠標滑過時候,將其設置為可見,默認情況下為隱藏。下面是一個小例子:
# -*- coding: UTF-8 -*- import matplotlib.pyplot as plt fig = plt.figure() po_annotation = [] for i in range(0, 10): x = i y = x**2 point, = plt.plot(x, y, 'o') annotation = plt.annotate(('x='+str(x), 'y='+str(y)), xy=(x+0.1, y+0.1), xycoords='data', xytext=(x+0.7, y+0.7), textcoords='data', horizontalalignment="left", arrowprops=dict(arrowstyle="simple",connectionstyle="arc3,rad=-0.1"), bbox=dict(boxstyle="round", facecolor="w",edgecolor="0.5", alpha=0.9) ) annotation.set_visible(False) po_annotation.append([point, annotation]) def on_move(event): visibility_changed = False for point, annotation in po_annotation: should_be_visible = (point.contains(event)[0] == True) # print(point.contains(event)[0]) if should_be_visible != annotation.get_visible(): visibility_changed = True annotation.set_visible(should_be_visible) if visibility_changed: plt.draw() on_move_id = fig.canvas.mpl_connect('motion_notify_event', on_move) plt.show()
主要思路為:
?創建[點,注釋]對的列表,默認情況下,注釋不可見
?每次檢測到鼠標移動時,都會注冊一個函數“on_move”
?on_move函數遍歷每個點和注釋,如果鼠標現在位于其中一個點上,則使其關聯的注釋可見,如果不是,則使其不可見。
運行出來的效果為: 當鼠標滑過時,可以顯示其相應坐標:
總結
以上所述是小編給大家介紹的python Matplotlib底圖中鼠標滑過顯示隱藏內容的實例代碼,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對腳本之家網站的支持!
如果你覺得本文對你有幫助,歡迎轉載,煩請注明出處,謝謝!
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
