python - 使用 matplotlib 修剪尾随 xticks 零

标签 python matplotlib

我对使用 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/

相关文章:

python - Docker容器入口点在挂载卷中没有此类文件错误

python - 我应该使用描述符类还是属性工厂?

python - 对 python 输入文件参数和标准输入流使用两个管道

python - Seaborn - 带 Bottom 参数的分组条形图

python - ValueError : Failed to find font DejaVu Sans:style=normal:variant=normal:weight=normal. ..并且回退到默认字体被禁用

Python nosetest 不起作用,但直接运行它可以使用 matplotlib 的 @image_comparison

python - 在 matplotlib 绘图上操作和动画图像

python - 从文件导入模块不起作用

python matplotlib : unable to call FuncAnimation from inside a function

Matplotlib 命名空间问题?