如何在线性与线性图上仅在y轴上转动次刻度?
当我使用函数minor_ticks_on
打开次要刻度时,它们出现在x和y轴上。
没关系,我明白了。
ax.tick_params(axis='x', which='minor', bottom=False)
这是我在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轴上放置小刻度线,因为默认情况下小刻度线是关闭的。
要在自定义位置设置次要刻度:
ax.set_xticks([0, 10, 20, 30], minor=True)
此外,如果您只想在实际的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()
为了澄清@ emad答案的过程,在默认位置显示次要刻度的步骤是:
一个最小的例子:
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轴上有小的刻度。