如何在线性与线性图上仅在 y 轴上转动小刻度?
当我使用该功能minor_ticks_on
打开小刻度时,它们同时出现在 x 和 y 轴上。
没关系,我想通了。
ax.tick_params(axis='x', which='minor', bottom=False)
这是我在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 轴上放置次要刻度,因为默认情况下次要刻度是关闭的。
为了澄清@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 轴上有小刻度。
在自定义位置设置次要刻度:
ax.set_xticks([0, 10, 20, 30], minor=True)
此外,如果您只想在实际的 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()
以下片段应该会有所帮助:
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.