91

如何在线性与线性图上仅在 y 轴上转动小刻度?

当我使用该功能minor_ticks_on打开小刻度时,它们同时出现在 x 和 y 轴上。

4

6 回答 6

64

没关系,我想通了。

ax.tick_params(axis='x', which='minor', bottom=False)
于 2012-10-03T15:29:04.873 回答
32

这是我在matplotlib 文档中找到的另一种方法:

import numpy as np
from matplotlib import pyplot as plt
from matplotlib.ticker import MultipleLocator

a = np.arange(100)
ml = MultipleLocator(5)
plt.plot(a)
plt.axes().yaxis.set_minor_locator(ml)
plt.show()

这将仅在 y 轴上放置次要刻度,因为默认情况下次要刻度是关闭的。

于 2012-10-03T15:40:08.870 回答
17

为了澄清@emad 的回答过程,在默认位置显示次要刻度的步骤是:

  1. 打开轴对象的小刻度,以便在 Matplotlib 认为合适的情况下初始化位置。
  2. 关闭不需要的次要刻度。

一个最小的例子:

import matplotlib.pyplot as plt

fig, ax = plt.subplots()
plt.plot([1,2])

# Currently, there are no minor ticks,
#   so trying to make them visible would have no effect
ax.yaxis.get_ticklocs(minor=True)     # []

# Initialize minor ticks
ax.minorticks_on()

# Now minor ticks exist and are turned on for both axes

# Turn off x-axis minor ticks
ax.xaxis.set_tick_params(which='minor', bottom=False)

替代方法

或者,我们可以使用以下命令在默认位置获取小刻度AutoMinorLocator

import matplotlib.pyplot as plt
import matplotlib.ticker as tck

fig, ax = plt.subplots()
plt.plot([1,2])

ax.yaxis.set_minor_locator(tck.AutoMinorLocator())

结果

无论哪种方式,生成的绘图仅在 y 轴上有小刻度。

仅在 y 轴上带有小刻度的绘图

于 2019-06-04T15:32:22.783 回答
14

在自定义位置设置次要刻度:

ax.set_xticks([0, 10, 20, 30], minor=True)
于 2018-01-07T10:42:03.887 回答
5

此外,如果您只想在实际的 y 轴上而不是在图表的左侧和右侧都需要小刻度,您可以遵循plt.axes().yaxis.set_minor_locator(ml)with plt.axes().yaxis.set_tick_params(which='minor', right = 'off'),如下所示:

import numpy as np
from matplotlib import pyplot as plt
from matplotlib.ticker import MultipleLocator

a = np.arange(100)
ml = MultipleLocator(5)
plt.plot(a)
plt.axes().yaxis.set_minor_locator(ml)
plt.axes().yaxis.set_tick_params(which='minor', right = 'off')
plt.show()
于 2016-12-31T09:06:38.290 回答
3

以下片段应该会有所帮助:

from matplotlib.ticker import MultipleLocator
ax.xaxis.set_minor_locator(MultipleLocator(#))
ax.yaxis.set_minor_locator(MultipleLocator(#))

# refers to the desired interval between minor ticks.
于 2020-12-25T18:45:01.470 回答