如何将热力图中的刻度和标签居中显示

3
我正在使用matplotlib绘制热力图,就像下面的图片一样:

matplotlib heatmap

这个图是通过以下代码构建的:
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()

我需要将两个坐标轴的刻度和标签居中。有什么想法吗?

请详细说明您想要放置刻度和标签的位置,以便更清楚地了解您的意图。 - Repiklis
@Repiklis 我希望标签(gamma和cost值)和刻度线位于每个框的中心。 - AdiT
1个回答

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()

result

如您所见,在此情况下,您需要关闭grid,否则它将与您的方块重叠并混乱您的图表。


1
这正是我所需要的。谢谢你。 - AdiT

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接