正如您所注意到的,它们默认情况下处于居中状态,您通过指定来覆盖默认行为
extent=[0, width, height, 0]。
有很多方法可以解决此问题。一种是使用
pcolor和设置edgecolors和linestyles看起来像网格线(你的实际需要
pcolor,而不是
pcolormesh为这个工作)。但是,您必须像
imshow默认情况下那样更改范围以使刻度线位于中心。
import matplotlib.pyplot as pltimport numpy as npdata = np.random.random((10,10))labels = 'abcdefghij'fig, ax = plt.subplots()im = ax.pcolor(data, cmap='gray', edgecolor='black', linestyle=':', lw=1)fig.colorbar(im)# Shift ticks to be at 0.5, 1.5, etcfor axis in [ax.xaxis, ax.yaxis]: axis.set(ticks=np.arange(0.5, len(labels)), ticklabels=labels)plt.show()
或者,您可以打开次网格并将其放置在像素边界处。由于您需要固定标签,因此我们将手动设置所有内容。否则,a
MultipleLocator会更有意义:
import matplotlib.pyplot as pltimport numpy as npdata = np.random.random((10,10))labels = 'abcdefghij'fig, ax = plt.subplots()im = ax.imshow(data, cmap='gray', interpolation='none')fig.colorbar(im)# Set the major ticks at the centers and minor tick at the edgeslocs = np.arange(len(labels))for axis in [ax.xaxis, ax.yaxis]: axis.set_ticks(locs + 0.5, minor=True) axis.set(ticks=locs, ticklabels=labels)# Turn on the grid for the minor ticksax.grid(True, which='minor')plt.show()



