How to centralized ticks and labels in a heatmap matplotlib
<p>I am plotting a heatmap using matplotlib like the figure below:</p>

<p><a href="http://i.stack.imgur.com/J8gmT.png" rel="nofollow"><img src="http://i.stack.imgur.com/J8gmT.png" alt="enter image description here"></a></p>

<p>The code snip below is used to achive the plot:</p>

<pre><code>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()
</code></pre>

<p>I need to centrelized the ticks and labels on both axes. Any idea? </p>

<p>For your specific code the simplest solution is to shift your tick positions by half a unit separation:</p>

<pre><code>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()
</code></pre>

<p><a href="http://i.stack.imgur.com/XkJ9c.png" rel="nofollow"><img src="http://i.stack.imgur.com/XkJ9c.png" alt="result"></a></p>

<p>As you can see, in this case you need to turn off the <code>grid</code>, otherwise it will overlap with your squares and clutter up your plot.</p>

python matplotlib label heatmap