如何自动在对数轴中设置次刻度?

时间:2018-06-28 17:38:01

标签: python python-3.x matplotlib axis-labels ticker

我正在寻找类似AutoMinorLocator的对数标度。

我知道默认情况下会启用次刻度线,但是调用.hist()方法会删除它们:

>>> ax.get_xticks(minor=True)
array([2.e-02, 3.e-02, 4.e-02, 5.e-02, 6.e-02, 7.e-02, 8.e-02, 9.e-02,
       2.e-01, 3.e-01, 4.e-01, 5.e-01, 6.e-01, 7.e-01, 8.e-01, 9.e-01,
       2.e+00, 3.e+00, 4.e+00, 5.e+00, 6.e+00, 7.e+00, 8.e+00, 9.e+00,
       2.e+01, 3.e+01, 4.e+01, 5.e+01, 6.e+01, 7.e+01, 8.e+01, 9.e+01,
       2.e+02, 3.e+02, 4.e+02, 5.e+02, 6.e+02, 7.e+02, 8.e+02, 9.e+02,
       2.e+03, 3.e+03, 4.e+03, 5.e+03, 6.e+03, 7.e+03, 8.e+03, 9.e+03]) 
>>> ax.hist([], bins=[1e-7, 1e-3])
(array([0.]), array([1.e-07, 1.e-03]), <a list of 1 Patch objects>)
>>> ax.get_xticks(minor=True)
array([], dtype=float64)

以下代码:

major = ax.get_xticks(minor=False)
ax.set_xticks(np.concatenate([np.linspace(0.2, 0.9, 8) * major.min()] +\
                             [np.linspace(1, 9, 9) * m
                              for m in major]),
              minor=True)

对于较小的滴答声效果很好,但是会破坏自动限制...

1 个答案:

答案 0 :(得分:0)

到目前为止,我最好的是:

start, end = ax01.get_xlim()
startLg = int(np.ceil(np.log10(start)))
endLg = int(np.floor(np.log10(end)))
major = np.logspace(startLg, endLg, endLg - startLg + 1)
ax.set_xticks([x for x in chain(np.linspace(0.2, 0.9, 8) * major.min(),
                                *[np.linspace(1, 9, 9) * m for m in major])
               if start <= x <= end],
              minor=True)

但是结果看起来并不惊人。

似乎Matplotlib会自动决定隐藏次要的刻度线,因为主要的刻度线每隔十年就会跳过一次:

>>> ax.hist([], bins=[1e-7, 1e-3])
(array([0.]), array([1.e-07, 1.e-03]), <a list of 1 Patch objects>)
>>> ax.get_xticks(minor=False)
array([1.e-10, 1.e-08, 1.e-06, 1.e-04, 1.e-02, 1.e+00])