Matplotlib: show shortcuts for small ticks also

In matplotlib , when I use the log scale on one axis, it can happen that this axis will have no major ticks , only minor ones . Thus, this means that there are no shortcuts for the entire axis.

How can I indicate that I need tags for small ticks?

I tried:

 plt.setp(ax.get_xticklabels(minor=True), visible=True) 

... but it did not help.

+8
python matplotlib plot axis-labels
source share
2 answers

I tried many ways for small ticks to work correctly in logarithmic graphs. If you're okay with showing the checkmark log, you can use matplotlib.ticker.LogFormatterExponent . I remember trying matplotlib.ticker.LogFormatter , but I didn’t like it: if I remember well, it puts everything in base^exp (also 0,1, 0, 1). In both cases (like all the other matplotlib.ticker.LogFormatter* ) you need to set labelOnlyBase=False to get minor ticks.

In the end, I created a custom function and used matplotlib.ticker.FuncFormatter . My approach assumes that ticks have integer values ​​and that you want to use a 10 log base.

 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 do not delete the main ticks and do not use subs = [2.0, 3.0, 6.0] , the font size of the main and minor ticks is different (this may be the reason using text.usetex:False in my matplotlibrc )

+5
source share

You can use set_minor_tickformatter on the corresponding axis:

 from matplotlib import pyplot as plt from matplotlib.ticker import FormatStrFormatter axes = plt.subplot(111) axes.loglog([3,4,7], [2,3,4]) axes.xaxis.set_minor_formatter(FormatStrFormatter("%.2f")) plt.xlim(1.8, 9.2) plt.show() 

enter image description here

+11
source share

All Articles