1 回答

TA貢獻1817條經驗 獲得超6個贊
您可以使用任何您想要的plt.FuncFormatter對象作為刻度標簽。
這是一個示例(確實是一個非常愚蠢的示例),請參閱優秀的 Matplotlib 文檔了解詳細信息。
import matplotlib.pyplot as plt
from numpy import arange
img = arange(21*21).reshape(21,21)
ax = plt.axes()
plt.imshow(img, origin='lower')
ax.xaxis.set_major_formatter(
plt.FuncFormatter(lambda x, pos: "$\\frac{%d}{20}$"%(200+x**2)))
每個軸都有一個major_formatter
負責生成刻度標簽的軸。
格式化程序必須是從 子類化的類的實例Formatter
,上面我們使用了FuncFormatter
.
要初始化 aFuncFormatter
我們向它傳遞一個格式化函數,我們必須使用以下必需的特征來定義它
有兩個輸入,
x
并且pos
是x
要格式化的橫坐標(或縱坐標),而pos
可以安全地忽略,返回要用作標簽的字符串。
在示例中,函數已使用lambda
語法在現場定義,其要點是格式化字符串 ( "$\\frac{%d}{20}$"%(200+x**2)
),將橫坐標函數格式化為LaTeX
分數,如上圖所示。
重新pos
參數,據我所知,它僅用于某些方法,例如
In [69]: ff = plt.FuncFormatter(lambda x, pos: "%r ? %05.2f"%(pos,x))
In [70]: ff.format_ticks((0,4,8,12))
Out[70]: ['0 ? 00.00', '1 ? 04.00', '2 ? 08.00', '3 ? 12.00']
但通常你可以忽略pos函數體中的參數。
添加回答
舉報