Matplotlib:还显示小刻度线的标签 [英] Matplotlib: show labels for minor ticks also

查看:93
本文介绍了Matplotlib:还显示小刻度线的标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

matplotlib中,当我在一个轴上使用log刻度时,可能会发生该轴没有大刻度线只有小刻度线的情况.因此,这意味着没有标签显示在整个轴上.

In matplotlib, when I use a log scale on one axis, it might happen that that axis will have no major ticks, only minor ones. So this means no labels are shown for the whole axis.

如何指定我的小滴答声也需要标签?

How can I specify that I need labels also for minor ticks?

我尝试过:

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

...但是没有成功.

... but it didn't do the trick.

推荐答案

我已经尝试了许多方法来使小刻度线在对数图中正常工作.如果您可以显示刻度值的日志,则可以使用 .我记得尝试过 matplotlib.ticker.LogFormatter ,但是我不太喜欢它:如果我还记得的话,它会将所有内容都放在base^exp中(也包含0.1、0、1).在这两种情况下(以及所有其他matplotlib.ticker.LogFormatter*),都必须设置labelOnlyBase=False以获得较小的滴答声.

I've tried many ways to get minor ticks working properly in log plots. If you are fine with showing the log of the value of the tick you can use matplotlib.ticker.LogFormatterExponent. I remember trying matplotlib.ticker.LogFormatter but I didn't like it much: if I remember well it puts everything in base^exp (also 0.1, 0, 1). In both cases (as well as all the other matplotlib.ticker.LogFormatter*) you have to set labelOnlyBase=False to get minor ticks.

我最终创建了一个自定义函数,并使用 matplotlib.ticker.FuncFormatter .我的方法假设刻度线为整数值,并且您希望以10为底的对数.

I ended up creating a custom function and use matplotlib.ticker.FuncFormatter. My approach assumes that the ticks are at integer values and that you want a base 10 log.

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],则主要和次要刻度线的字体大小会有所不同(这可能是由于在我的matplotlibrc中使用text.usetex:False导致的)

If you don't remove the major ticks and use subs = [2.0, 3.0, 6.0] the font size of the major and minor ticks is different (this might be cause by using text.usetex:False in my matplotlibrc)

这篇关于Matplotlib:还显示小刻度线的标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆