为了账号安全,请及时绑定邮箱和手机立即绑定

Matplotlib:还显示小刻度线的标签

Matplotlib:还显示小刻度线的标签

陪伴而非守候 2021-03-29 09:48:14
在中matplotlib,当我log在一个轴上使用刻度时,可能会发生该轴没有大刻度线的情况,只有小刻度线的情况。因此,这意味着整个轴都不会显示标签。如何指定我的小滴答声也需要标签?我试过:plt.setp(ax.get_xticklabels(minor=True), visible=True)...但是它并不能解决问题。
查看完整描述

4 回答

?
莫回无

TA贡献1865条经验 获得超7个赞

我尝试了许多方法来使小刻度线在对数图中正常工作。如果您可以显示刻度值的对数,则可以使用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)


查看完整回答
反对 回复 2021-04-02
  • 4 回答
  • 0 关注
  • 652 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号