用matplotlib修剪尾随xticks零 [英] Trimming trailing xticks zeros with matplotlib

查看:58
本文介绍了用matplotlib修剪尾随xticks零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

非常不熟悉使用matplotlib,并且在使用xticks时遇到了困难.我基本上有一个从0到0.025的x轴.我的问题出现是因为 x 轴上 most 精确值的精度似乎为它们设置了所有精度,例如0显示为0.000.我希望它显示为 0,因为尾随零是多余的,其他值也类似.

I'm very new to using matplotlib, and I'm having difficulty with the xticks. I basically have an x axis from 0 to 0.025. My problem arises since the precision of the most precise value in the x axis seems to set the precision for them all, so e.g. 0 appears as 0.000. I'd like it to appear as 0 since the trailing zeroes are redundant and analogously for the other values.

这就是我所拥有的...输出在x轴上给出了太多的尾随零:

Here is what I have... the output gives too many trailing zeroes on the x axis:

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,所以这不是一个想法解决方案.

Is there an obvious way to do what I'd like, or am I stuck with it? I used PyX previously (and I must admit I'm getting a bit muddled as I've learned to use each purely through the use of stuff my collaborators have used and they've varied between), which sets the axes properly, but doesn't seem to support LaTeX as well as I'd like, so it's not an idea solution.

推荐答案

您需要的是以下两行:

from matplotlib.ticker import FormatStrFormatter
plt.gca().xaxis.set_major_formatter(FormatStrFormatter('%g'))

FormatStrFormatter 可以接受其他类似sprintf的格式设置选项.

The FormatStrFormatter can accept other sprintf-like formatting options.

这篇关于用matplotlib修剪尾随xticks零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆