Reputation: 549
I am plotting a heatmap using matplotlib like the figure below:
The plot is constructed via the code below:
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()
I need to center the ticks and labels on both axes. Any ideas?
Upvotes: 3
Views: 10781
Reputation: 35094
For your specific code the simplest solution is to shift your tick positions by half a unit separation:
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()
As you can see, in this case you need to turn off the grid
, otherwise it will overlap with your squares and clutter up your plot.
Upvotes: 5