繁体   English   中英

如何使用 Matplotlib 在对数刻度上显示次要刻度标签

[英]How to show minor tick labels on log-scale with Matplotlib

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

您可以使用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()

在此处输入图片说明

一种选择是使用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)

你会得到

小蜱虫

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM