Matplotlib:显示次要蜱的标签

时间:2013-06-18 09:37:22

标签: python matplotlib plot axis-labels

matplotlib中,当我在一个轴上使用log刻度时,可能会发生该轴无主要刻度仅次要一个。所以这意味着整个轴都显示没有标签

如何指定我还需要标注小标记?

我试过了:

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

......但它并没有成功。

3 个答案:

答案 0 :(得分:12)

您可以在相应的轴上使用set_minor_tickformatter

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

答案 1 :(得分:6)

我已经尝试了很多方法让小标记在日志图中正常工作。如果您可以使用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

答案 2 :(得分:0)

我认为值得一提的是matplotlib 2.0版(docs link)中引入的选项“ minor_thresholds”。它是LogFormatter类的一对(子集,全部)形式的参数,可让您指定何时应显示次要剔号标签的(固定)子集以及何时应显示所有次要剔号标签(这意味着什么)在底部)。

在下面的代码中,我通过使用相同的参数值(在这种情况下为(2,0.4))但改变了x轴的限制来显示效果:

import matplotlib.pyplot as plt
from matplotlib.ticker import LogFormatter
import numpy as np

fig, axes = plt.subplots(4, figsize=(12, 24))

dt = 0.01
t = np.arange(dt, 20.0, dt)

# first plot doesn't use a formatter
axes[0].semilogx(t, np.exp(-t / 5.0))
axes[0].set_xlim([0, 25])
axes[0].grid()

xlims = [[0, 25], [0.2, 8], [0.6, 0.9]]

for ax, xlim in zip(axes[1:], xlims):
    ax.semilogx(t, np.exp(-t / 5.0))
    formatter = LogFormatter(labelOnlyBase=False, minor_thresholds=(2, 0.4))
    ax.get_xaxis().set_minor_formatter(formatter)
    ax.set_xlim(xlim)
    ax.grid()

plt.show()

这将导致以下绘图: enter image description here

您会看到,在第二行中,刻度标签与我们未使用格式化程序的第一行中的相同。这是因为视图范围的对数大于2(参数对的第一个值),或者换句话说,视图的范围大于两个主要刻度标签之间的范围。在第三行中,视图小于2但大于0.4(参数对的第二个值),因此我们看到了次要刻度标签的子集。最后,在最后一行中,视图跨越两个主要刻度标签之间的空间不到0.4,因此显示了所有次要刻度标签。