使用matplotlib去掉尾部零的xticks
我对使用matplotlib还很陌生,最近在处理x轴的刻度时遇到了一些困难。我的x轴范围是从0到0.025。问题在于,x轴上最精确的值似乎决定了所有值的显示精度,比如0这个值显示成了0.000。我希望它能显示成0,因为后面的零是多余的,其他值也是同样的情况。
这是我目前的代码……输出的x轴上有太多多余的零:
from matplotlib import rc
from matplotlib import pyplot
import matplotlib.pyplot as plt
rc('font', **{'family': 'serif', 'serif': ['Computer Modern']})
rc('text', usetex = True)
xmin=0
xmax=0.4
ymin=4.0
ymax=4.5
asq=[0.0217268]
mb=[4.1929]
mberr=[0.0055]
# some arguments for points etc...
ebargs = dict(mfc='None',alpha=1,ms=8,
capsize=1.75,elinewidth=0.75,mew=0.75)
fw = 4.5 # width
fh = fw/1.618 # height
plt.rc('figure',figsize=(fw,fh))
plt.xlim(xmin,xmax)
plt.ylim(ymin,ymax)
plt.errorbar(x=[x for x in asq],
y=[y for y in mb],
yerr=[yerr for yerr in mberr],
fmt='o',c='b',mec='b', **ebargs
)
plt.savefig("mb-plot.pdf",bbox_inches='tight')
有没有简单的方法可以解决我的问题,还是我就只能这样了?我之前用过PyX(我得承认,我有点搞混了,因为我都是通过我的同事使用的工具来学习的,他们用的工具各不相同),PyX能正确设置坐标轴,但在支持LaTeX方面不如我希望的那样好,所以这不是一个理想的解决方案。
1 个回答
6
你需要这两行代码:
from matplotlib.ticker import FormatStrFormatter
plt.gca().xaxis.set_major_formatter(FormatStrFormatter('%g'))
FormatStrFormatter 可以接受其他类似于 sprintf 的格式选项。