如何在热图中居中显示刻度线和标签

Adi*_*diT 3 python label data-visualization matplotlib heatmap

我正在使用 matplotlib 绘制热图,如下图所示:

matplotlib 热图

该图是通过以下代码构建的:

C_range = 10. ** np.arange(-2, 8)
gamma_range = 10. ** np.arange(-5, 4)

confMat=np.random.rand(10, 9)

heatmap = plt.pcolor(confMat)

for y in range(confMat.shape[0]):
    for x in range(confMat.shape[1]):
        plt.text(x + 0.5, y + 0.5, '%.2f' % confMat[y, x],
                horizontalalignment='center',
                verticalalignment='center',)


plt.grid()
plt.colorbar(heatmap)
plt.subplots_adjust(left=0.15, right=0.99, bottom=0.15, top=0.99)
plt.ylabel('Cost')
plt.xlabel('Gamma')

plt.xticks(np.arange(len(gamma_range)), gamma_range, rotation=45,)
plt.yticks(np.arange(len(C_range)), C_range, rotation=45)
plt.show()
Run Code Online (Sandbox Code Playgroud)

我需要将刻度和标签在两个轴上居中。有任何想法吗?

And*_*eak 5

对于您的特定代码,最简单的解决方案是将刻度位置移动半个单位间隔:

import numpy as np
import matplotlib.pyplot as plt

C_range = 10. ** np.arange(-2, 8)
gamma_range = 10. ** np.arange(-5, 4)

confMat=np.random.rand(10, 9)

heatmap = plt.pcolor(confMat)

for y in range(confMat.shape[0]):
    for x in range(confMat.shape[1]):
        plt.text(x + 0.5, y + 0.5, '%.2f' % confMat[y, x],
                horizontalalignment='center',
                verticalalignment='center',)


#plt.grid() #this will look bad now
plt.colorbar(heatmap)
plt.subplots_adjust(left=0.15, right=0.99, bottom=0.15, top=0.99)
plt.ylabel('Cost')
plt.xlabel('Gamma')

plt.xticks(np.arange(len(gamma_range))+0.5, gamma_range, rotation=45,)
plt.yticks(np.arange(len(C_range))+0.5, C_range, rotation=45)
plt.show()
Run Code Online (Sandbox Code Playgroud)

结果

正如您所看到的,在这种情况下,您需要关闭grid,否则它将与您的方块重叠并使您的绘图变得混乱。