4 回答

TA贡献1865条经验 获得超7个赞
我尝试了许多方法来使小刻度线在对数图中正常工作。如果您可以显示刻度值的对数,则可以使用matplotlib.ticker.LogFormatterExponent。我记得尝试过,matplotlib.ticker.LogFormatter但是我不太喜欢它:如果我没记错的话,它会将所有内容放入base^exp(也包括0.1、0、1)。在这两种情况下(以及所有其他情况下matplotlib.ticker.LogFormatter*),您都必须设置labelOnlyBase=False为获得较小的滴答声。
我最终创建了一个自定义函数并使用matplotlib.ticker.FuncFormatter。我的方法假设刻度线为整数值,并且您希望以10为底的对数。
from matplotlib import ticker
import numpy as np
def ticks_format(value, index):
"""
get the value and returns the value as:
integer: [0,99]
1 digit float: [0.1, 0.99]
n*10^m: otherwise
To have all the number of the same size they are all returned as latex strings
"""
exp = np.floor(np.log10(value))
base = value/10**exp
if exp == 0 or exp == 1:
return '${0:d}$'.format(int(value))
if exp == -1:
return '${0:.1f}$'.format(value)
else:
return '${0:d}\\times10^{{{1:d}}}$'.format(int(base), int(exp))
subs = [1.0, 2.0, 3.0, 6.0] # ticks to show per decade
ax.xaxis.set_minor_locator(ticker.LogLocator(subs=subs)) #set the ticks position
ax.xaxis.set_major_formatter(ticker.NullFormatter()) # remove the major ticks
ax.xaxis.set_minor_formatter(ticker.FuncFormatter(ticks_format)) #add the custom ticks
#same for ax.yaxis
如果您不删除主要刻度线并使用主要刻度线和subs = [2.0, 3.0, 6.0]次要刻度线的字体大小是不同的(这可能是由于text.usetex:False在我的中使用引起的matplotlibrc)
添加回答
举报