我对使用 matplotlib 非常陌生,并且在使用 xticks 时遇到困难。我基本上有一个从 0 到 0.025 的 x 轴。我的问题出现了,因为 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(我必须承认我有点困惑,因为我纯粹通过使用我的合作者使用过的东西来学习使用它们,并且它们之间有所不同),它正确地设置了轴,但没有似乎没有像我希望的那样支持 LaTeX,所以这不是一个理想的解决方案。
最佳答案
您需要的是这两行:
from matplotlib.ticker import FormatStrFormatter
plt.gca().xaxis.set_major_formatter(FormatStrFormatter('%g'))
FormatStrFormatter可以接受其他类似 sprintf 的格式选项。
关于python - 使用 matplotlib 修剪尾随 xticks 零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25274689/