Matplotlib 在使用子图时不会显示小刻度
Matplotlib won't show minor ticks when using subplots
我有几个子图,想通过 ax.tick_params 调整轴刻度设置。一切正常,但是,未显示 minor 刻度。这是一个代码示例
import matplotlib.pyplot as plt
x = np.linspace(0,1,100)
y = x*x
f, (ax1,ax2) = plt.subplots(2, 1)
ax1.tick_params(axis="both", direction="in", which="both", right=False, top=True)
ax2.tick_params(axis="both", direction="in", which="both", right=True, top=False)
ax1.plot(x,y)
ax2.plot(x,-y)
plt.show()
我假设 which=both 会给我小的滴答声。但是我需要添加一个额外的
plt.minorticks_on()
这使得它们在 ax2 中可见 但仅。
我该如何解决这个问题?
使用 pyplot 的危险在于,您无法跟踪当前轴是像 plt.minorticks_on()
这样的命令所操作的轴。因此,使用您正在使用的轴的相应方法将是有益的:
ax1.minorticks_on()
ax2.minorticks_on()
plt
将在当前轴上工作,在您的情况下为 ax2
。一种方法是首先使用您所做的方式启用它们,然后使用 AutoMinorLocator
指定次要刻度数
from matplotlib.ticker import AutoMinorLocator
ax1.tick_params(axis="both", direction="in", which="both", right=False, top=True)
ax2.tick_params(axis="both", direction="in", which="both", right=True, top=False)
ax1.plot(x,y)
ax2.plot(x,-y)
for ax in [ax1, ax2]:
ax.xaxis.set_minor_locator(AutoMinorLocator(4))
ax.yaxis.set_minor_locator(AutoMinorLocator(4))
我有几个子图,想通过 ax.tick_params 调整轴刻度设置。一切正常,但是,未显示 minor 刻度。这是一个代码示例
import matplotlib.pyplot as plt
x = np.linspace(0,1,100)
y = x*x
f, (ax1,ax2) = plt.subplots(2, 1)
ax1.tick_params(axis="both", direction="in", which="both", right=False, top=True)
ax2.tick_params(axis="both", direction="in", which="both", right=True, top=False)
ax1.plot(x,y)
ax2.plot(x,-y)
plt.show()
我假设 which=both 会给我小的滴答声。但是我需要添加一个额外的
plt.minorticks_on()
这使得它们在 ax2 中可见 但仅。
我该如何解决这个问题?
使用 pyplot 的危险在于,您无法跟踪当前轴是像 plt.minorticks_on()
这样的命令所操作的轴。因此,使用您正在使用的轴的相应方法将是有益的:
ax1.minorticks_on()
ax2.minorticks_on()
plt
将在当前轴上工作,在您的情况下为 ax2
。一种方法是首先使用您所做的方式启用它们,然后使用 AutoMinorLocator
from matplotlib.ticker import AutoMinorLocator
ax1.tick_params(axis="both", direction="in", which="both", right=False, top=True)
ax2.tick_params(axis="both", direction="in", which="both", right=True, top=False)
ax1.plot(x,y)
ax2.plot(x,-y)
for ax in [ax1, ax2]:
ax.xaxis.set_minor_locator(AutoMinorLocator(4))
ax.yaxis.set_minor_locator(AutoMinorLocator(4))