微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

更改日志图中的刻度标签

如何解决更改日志图中的刻度标签

认绘图将科学记数法放在 x 轴标签中。这些标签是 2、3、4 和 6,所以没有多大意义。传统方法似乎依赖于'ScalarFormatter',它不在日志空间中使用...

import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit


nu = np.array([34.,10.,3.,2.,1.])
bins = np.array([1.73619534,2.6928761,3.64955685,4.6062376,6.5195991 ])
x_err = (bins[2]-bins[1])/2*(nu/nu)

def func_powerlaw(x,m,c):
    return x**m * c
target_func = func_powerlaw
popt,pcov = curve_fit(target_func,bins,nu,maxfev=2000,p0 = np.asarray([-1,34]))
perr = np.sqrt(np.diag(pcov))
x_line = np.linspace(1.7,6.7,41)
fit_curve = target_func(x_line,*popt)
fit_curve_u = target_func(x_line,popt[0]+perr[0],popt[1]+perr[1])
fit_curve_l = target_func(x_line,popt[0]-perr[0],popt[1]-perr[1])


fig,ax = plt.subplots()
# plt.loglog(x,f_x,'b')
ax.errorbar(bins,yerr=None,xerr=x_err,marker='.',linewidth = 0,elinewidth=2,color = 'k')
ax.loglog(x_line,fit_curve,'-')
ax.fill_between(x_line,fit_curve_l,fit_curve_u,alpha = 0.2)
# labels = ['high','low',37337]
ax.set_xscale('log') # yes this is redundant
ax.set_xticks([2,3,4,5]) #this line ends up not working ):
ax.set_xlim([1.5,8.5])

plot you get from running the code

解决方法

这个问题是重复的,在这里找到答案:How to change log-scale tick labels in matplotlib

答案:

from matplotlib.ticker import StrMethodFormatter,NullFormatter
ax.xaxis.set_major_formatter(StrMethodFormatter('{x:.1f}'))
ax.xaxis.set_minor_formatter(NullFormatter())

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。