如何在Matplotlib中显示对数刻度的次要刻度标签

24

有人知道如何使用Python/Matplotlib在对数刻度上显示小刻度的标签吗?


你看过函数set_tick_params()了吗?文档说明:设置刻度线和刻度标签的外观参数。 - prodev_paris
这个问题似乎是https://dev59.com/AWQn5IYBdhLWcg3wAjTJ#17167748的重复。 - prodev_paris
如果有人正在寻找一种解决方案来显示跨越10个数量级以上的对数轴上的次刻度线,那么下面的解决方案将无法工作,可以看看这个问题 - ImportanceOfBeingErnest
2个回答

23
你可以使用 plt.tick_params(axis='y', which='minor') 来设置并用 matplotlib.ticker 中的 FormatStrFormatter 对次要刻度进行格式化。例如,
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import FormatStrFormatter
x = np.linspace(0,4,1000)
y = np.exp(x)
plt.plot(x, y)
ax = plt.gca()
ax.set_yscale('log')
plt.tick_params(axis='y', which='minor')
ax.yaxis.set_minor_formatter(FormatStrFormatter("%.1f"))
plt.show()

在此输入图片描述


我认为OP更多地是想在次要刻度上添加一些标签,就像这个相关答案中所示:https://dev59.com/AWQn5IYBdhLWcg3wAjTJ#17167748 - prodev_paris
@prodev_paris -- 你说得对:我已经编辑了我的答案,使其更加完整。 - xnx
1
@xnx 有没有一种方法可以为每个第_n_个次要刻度标记标签?例如类似于 plt.tick_params(axis='x', which='minor', every=6) 的东西。 - 3kstc
更好的是,打开网格! - Bill N

12

一个选择是使用matplotlib.ticker.LogLocator

import numpy
import pylab
import matplotlib.pyplot
import matplotlib.ticker
## setup styles
from  matplotlib import rc
rc('font', **{'family': 'sans-serif', 'sans-serif': ['Times-Roman']})
rc('text', usetex = True)
matplotlib.rcParams['text.latex.preamble'] = [r"\usepackage{amsmath}"]

## make figure
figure, ax = matplotlib.pyplot.subplots(1, sharex = True, squeeze = True)
x = numpy.linspace(0.0, 20.0, 1000)
y = numpy.exp(x)
ax.plot(x, y)
ax.set_yscale('log')

## set y ticks
y_major = matplotlib.ticker.LogLocator(base = 10.0, numticks = 5)
ax.yaxis.set_major_locator(y_major)
y_minor = matplotlib.ticker.LogLocator(base = 10.0, subs = numpy.arange(1.0, 10.0) * 0.1, numticks = 10)
ax.yaxis.set_minor_locator(y_minor)
ax.yaxis.set_minor_formatter(matplotlib.ticker.NullFormatter())

## save figure
pylab.tight_layout()
pylab.savefig('./test.png', dpi = 200)

您将会得到:

minor ticks

唯一需要手动调整的是主要和次要刻度线的numticks输入,它们都必须是主要刻度线总数的一部分。


1
这对我有用,我在这里遇到了类似的问题 https://stackoverflow.com/questions/65727726/matplotlib-add-gridlines-not-working-as-expected? - a11

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接