如何仅在y轴matplotlib上打开次要刻度

问题描述 投票:57回答:5

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

当我使用函数minor_ticks_on打开次要刻度时,它们出现在x和y轴上。

python matplotlib
5个回答
46
投票

没关系,我明白了。

ax.tick_params(axis='x', which='minor', bottom=False)

22
投票

这是我在matplotlib documentation找到的另一种方式:

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轴上放置小刻度线,因为默认情况下小刻度线是关闭的。


6
投票

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

ax.set_xticks([0, 10, 20, 30], minor=True)

5
投票

此外,如果您只想在实际的y轴上进行小刻度,而不是在图的左侧和右侧,您可以使用plt.axes().yaxis.set_minor_locator(ml)跟随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()

0
投票

为了澄清@ 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轴上有小的刻度。

plot with minor ticks on y-axis only

© www.soinside.com 2019 - 2024. All rights reserved.