【问题标题】:How to show minor tick labels on log-scale with Matplotlib如何使用 Matplotlib 在对数刻度上显示次要刻度标签
【发布时间】:2015-09-02 11:20:00
【问题描述】:

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

【问题讨论】:

标签: python matplotlib


【解决方案1】:

您可以使用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 的要求更多,因为他希望在小蜱上贴上一些标签。就像在这个相关答案中一样:stackoverflow.com/a/17167748/4716013
  • @prodev_paris -- 你是对的:我已经编辑了我的答案以使其更完整。
  • @xnx 有没有办法标记每个 n 次小刻度?例如plt.tick_params(axis='x', which='minor', every=6)
  • 更好的是,打开网格!
【解决方案2】:

一种选择是使用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 输入,它们都必须是可能的主要刻度总数的一小部分。

【讨论】:

猜你喜欢
  • 2013-06-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-22
  • 2018-06-03
相关资源
最近更新 更多