Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trimming trailing xticks zeros with matplotlib

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.

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')

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.

like image 646
Article 82 Avatar asked Sep 17 '25 06:09

Article 82


1 Answers

What you need are these two lines:

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

The FormatStrFormatter can accept other sprintf-like formatting options.

like image 109
Korem Avatar answered Sep 18 '25 18:09

Korem