我一直在与你所展示的类似的东西进行斗争(轴范围内只有一个主要刻度)。 matplotlib 刻度格式化程序都不让我满意,所以我使用matplotlib.ticker.FuncFormatter
来实现我想要的。我还没有使用双轴进行测试,但我的感觉是它应该可以工作。
import matplotlib.pyplot as plt
from matplotlib import ticker
import numpy as np
#@Mark: thanks for the suggestion :D
mi, ma, conv = 4, 8, 1./3.
x = np.linspace(mi, ma, 20)
y = 1 / (x ** 4)
fig, ax = plt.subplots()
ax.plot(x, y) # plot the lines
ax.set_xscale('log') #convert to log
ax.set_yscale('log')
ax.set_xlim([0.2, 1.8]) #large enough, but should show only 1 tick
def ticks_format(value, index):
"""
This function decompose value in base*10^{exp} and return a latex string.
If 0<=value<99: return the value as it is.
if 0.1<value<0: returns as it is rounded to the first decimal
otherwise returns $base*10^{exp}$
I've designed the function to be use with values for which the decomposition
returns integers
"""
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))
# here specify which minor ticks per decate you want
# likely all of them give you a too crowed axis
subs = [1., 3., 6.]
# set the minor locators
ax.xaxis.set_minor_locator(ticker.LogLocator(subs=subs))
ax.yaxis.set_minor_locator(ticker.LogLocator(subs=subs))
# remove the tick labels for the major ticks:
# if not done they will be printed with the custom ones (you don't want it)
# plus you want to remove them to avoid font missmatch: the above function
# returns latex string, and I don't know how matplotlib does exponents in labels
ax.xaxis.set_major_formatter(ticker.NullFormatter())
ax.yaxis.set_major_formatter(ticker.NullFormatter())
# set the desired minor tick labels using the above function
ax.xaxis.set_minor_formatter(ticker.FuncFormatter(ticks_format))
ax.yaxis.set_minor_formatter(ticker.FuncFormatter(ticks_format))
The figure that I get is the following
:
当然,您可以为 x 轴和 y 轴设置不同的次要定位器,并且可以将所有内容包装起来ticks_format
到最后进入接受轴实例的函数ax
and subs
or subsx
and subsy
作为输入参数。
我希望这对你有帮助