使用用户函数来定义刻度格式,func的参数需要有两个,一个是x的值,一个是位置参数;返回值是对应位置的字符串。
FuncFormatter的返回值是一个formatter对象。
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.ticker import FuncFormatter,AutoMinorLocator,MultipleLocator
x=np.linspace(0.5,3.5,100)
y=np.sin(x)
def func(x,pos):
if not x%1.0:
return " "
return "%.2f"%x
fig,ax=plt.subplots(figsize=(8,8))
ax.xaxis.set_major_locator(MultipleLocator(1.0))
ax.xaxis.set_minor_locator(AutoMinorLocator(4))
ax.xaxis.set_minor_formatter(FuncFormatter(func))
ax.tick_params("x",which='minor',length=5,width=1.0,labelsize=5,labelcolor='0.25')
ax.plot(x,y)
plt.show()