Matplotlib: show labels for minor ticks also

前端 未结 3 977
野趣味
野趣味 2020-12-09 20:21

In matplotlib, when I use a log scale on one axis, it might happen that that axis will have no major ticks, only minor

3条回答
  •  情歌与酒
    2020-12-09 20:49

    I've tried many ways to get minor ticks working properly in log plots. If you are fine with showing the log of the value of the tick you can use matplotlib.ticker.LogFormatterExponent. I remember trying matplotlib.ticker.LogFormatter but I didn't like it much: if I remember well it puts everything in base^exp (also 0.1, 0, 1). In both cases (as well as all the other matplotlib.ticker.LogFormatter*) you have to set labelOnlyBase=False to get minor ticks.

    I ended up creating a custom function and use matplotlib.ticker.FuncFormatter. My approach assumes that the ticks are at integer values and that you want a base 10 log.

    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
    

    If you don't remove the major ticks and use subs = [2.0, 3.0, 6.0] the font size of the major and minor ticks is different (this might be cause by using text.usetex:False in my matplotlibrc)

提交回复
热议问题