1. 程式人生 > 程式設計 >matplotlib自定義滑鼠游標座標格式的實現

matplotlib自定義滑鼠游標座標格式的實現

matplotlib預設在影象Windows視窗中顯示當前滑鼠游標所在位置的座標,格式為x=xx,y=xx

滑鼠游標的座標格式由子圖模組Axes中的format_coord函式控制。

通過重寫format_coord函式即可實現座標的自定義格式。

注意:呼叫format_coord函式的物件是子圖物件,常見的錯誤主要在沒有正確的獲取當前子圖物件。

在這裡插入圖片描述

format_coord函式原始碼

matplotlib.axes.Axes.format_coord

def format_coord(self,x,y):
  """Return a format string formatting the *x*,*y* coordinates."""
  if x is None:
    xs = '???'
  else:
    xs = self.format_xdata(x)
  if y is None:
    ys = '???'
  else:
    ys = self.format_ydata(y)
  return 'x=%s y=%s' % (xs,ys)

自定義座標格式實現

import matplotlib.pyplot as plt

def format_coord(x,y):
  return 'x座標為%1.4f,y座標為%1.4f' % (x,y)
#獲取當前子圖
ax=plt.gca()
ax.format_coord = format_coord
plt.show()

在這裡插入圖片描述

到此這篇關於matplotlib自定義滑鼠游標座標格式的實現的文章就介紹到這了,更多相關matplotlib自定義滑鼠游標座標內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!